blob: a225f60291b8968b0d5966f421fbd3b62e6eb7e4 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070020#include <iostream>
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070022#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
Andreas Gampea696c0a2014-12-10 20:51:45 -080024#include <unistd.h>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027
Elliott Hughes1aa246d2012-12-13 09:29:36 -080028#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080029#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010030#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080031#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080032#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000034#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080035#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070037#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070038#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap.h"
41#include "gc/heap.h"
42#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070043#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070044#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070045#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070046#include "leb128.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080047#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070048#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070049#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070050#include "mirror/art_field-inl.h"
51#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/class.h"
53#include "mirror/class-inl.h"
54#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070055#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/object-inl.h"
58#include "mirror/object_array-inl.h"
59#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070060#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070062#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080063#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070064#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070065#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070066#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070067#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070068#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070069#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070070#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080071#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070072#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070073
74namespace art {
75
Ian Rogers00f7d0e2012-07-19 15:28:27 -070076static void ThrowNoClassDefFoundError(const char* fmt, ...)
77 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070078 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070079static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070080 va_list args;
81 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080082 Thread* self = Thread::Current();
83 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
84 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080085 va_end(args);
86}
87
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080088static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070090 // The class failed to initialize on a previous attempt, so we want to throw
91 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
92 // failed in verification, in which case v2 5.4.1 says we need to re-throw
93 // the previous error.
Ian Rogers7b078e82014-09-10 14:44:24 -070094 Runtime* runtime = Runtime::Current();
95 bool is_compiler = runtime->IsCompiler();
96 if (!is_compiler) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070097 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
98 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070099
Elliott Hughes5c599942012-06-13 16:45:05 -0700100 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800101 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700102 if (is_compiler) {
103 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
104 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
105 self->SetException(ThrowLocation(), pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700106 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700107 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
108 if (c->GetVerifyErrorClass() != NULL) {
109 // TODO: change the verifier to store an _instance_, with a useful detail message?
110 std::string temp;
111 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
112 PrettyDescriptor(c).c_str());
113 } else {
114 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
115 PrettyDescriptor(c).c_str());
116 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700117 }
118}
119
Brian Carlstromb23eab12014-10-08 17:55:21 -0700120static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
121 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
122 if (VLOG_IS_ON(class_linker)) {
123 std::string temp;
124 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
125 << klass->GetLocation() << "\n" << Thread::Current()->GetException(nullptr)->Dump();
126 }
127}
128
129static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
130 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700131 Thread* self = Thread::Current();
132 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700133
134 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700135 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700136
137 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700138 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
139 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700140
Elliott Hughesa4f94742012-05-29 16:28:38 -0700141 // We only wrap non-Error exceptions; an Error can just be used as-is.
142 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800143 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700144 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
145 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700146 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700147 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700148}
149
Fred Shih381e4ca2014-08-25 17:24:27 -0700150// Gap between two fields in object layout.
151struct FieldGap {
152 uint32_t start_offset; // The offset from the start of the object.
153 uint32_t size; // The gap size of 1, 2, or 4 bytes.
154};
155struct FieldGapsComparator {
156 explicit FieldGapsComparator() {
157 }
158 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
159 NO_THREAD_SAFETY_ANALYSIS {
160 // Sort by gap size, largest first.
161 return lhs.size > rhs.size;
162 }
163};
164typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
165
166// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800167static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700168 DCHECK(gaps != nullptr);
169
170 uint32_t current_offset = gap_start;
171 while (current_offset != gap_end) {
172 size_t remaining = gap_end - current_offset;
173 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
174 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
175 current_offset += sizeof(uint32_t);
176 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
177 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
178 current_offset += sizeof(uint16_t);
179 } else {
180 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
181 current_offset += sizeof(uint8_t);
182 }
183 DCHECK_LE(current_offset, gap_end) << "Overran gap";
184 }
185}
186// Shuffle fields forward, making use of gaps whenever possible.
187template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000188static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700189 MemberOffset* field_offset,
Fred Shih381e4ca2014-08-25 17:24:27 -0700190 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
191 FieldGaps* gaps)
192 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
193 DCHECK(current_field_idx != nullptr);
194 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700195 DCHECK(gaps != nullptr);
196 DCHECK(field_offset != nullptr);
197
198 DCHECK(IsPowerOfTwo(n));
199 while (!grouped_and_sorted_fields->empty()) {
200 mirror::ArtField* field = grouped_and_sorted_fields->front();
201 Primitive::Type type = field->GetTypeAsPrimitiveType();
202 if (Primitive::ComponentSize(type) < n) {
203 break;
204 }
205 if (!IsAligned<n>(field_offset->Uint32Value())) {
206 MemberOffset old_offset = *field_offset;
207 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
208 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
209 }
210 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
211 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700212 if (!gaps->empty() && gaps->top().size >= n) {
213 FieldGap gap = gaps->top();
214 gaps->pop();
215 DCHECK(IsAligned<n>(gap.start_offset));
216 field->SetOffset(MemberOffset(gap.start_offset));
217 if (gap.size > n) {
218 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
219 }
220 } else {
221 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
222 field->SetOffset(*field_offset);
223 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
224 }
225 ++(*current_field_idx);
226 }
227}
228
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800229ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700230 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700231 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700232 dex_cache_image_class_lookup_required_(false),
233 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800234 class_roots_(nullptr),
235 array_iftable_(nullptr),
236 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700237 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800238 log_new_dex_caches_roots_(false),
239 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700240 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800241 portable_resolution_trampoline_(nullptr),
242 quick_resolution_trampoline_(nullptr),
243 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800244 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100245 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800246 quick_to_interpreter_bridge_trampoline_(nullptr),
247 image_pointer_size_(sizeof(void*)) {
Ian Rogers98379392014-02-24 16:53:16 -0800248 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700249}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700250
Alex Light64ad14d2014-08-19 14:23:13 -0700251void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800252 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700253 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700254
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700255 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700256
Elliott Hughes30646832011-10-13 16:59:46 -0700257 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700258 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700259 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700260 // The GC can't handle an object with a null class since we can't get the size of this object.
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800261 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700262 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
263 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700264 heap->AllocNonMovableObject<true>(self, nullptr,
265 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700266 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700267 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700268 mirror::Class::SetClassClass(java_lang_Class.Get());
269 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700270 if (kUseBakerOrBrooksReadBarrier) {
271 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800272 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700273 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700274 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800275 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800276 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700277
Elliott Hughes418d20f2011-09-22 14:00:39 -0700278 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700279 Handle<mirror::Class> class_array_class(hs.NewHandle(
280 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700281 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700282
Ian Rogers23435d02012-09-24 11:23:12 -0700283 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700284 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
285 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700286 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700287 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700288 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700289 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700290
Ian Rogers23435d02012-09-24 11:23:12 -0700291 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700292 Handle<mirror::Class> object_array_class(hs.NewHandle(
293 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700294 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700295
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700296 // Setup the char (primitive) class to be used for char[].
297 Handle<mirror::Class> char_class(hs.NewHandle(
298 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700299 // The primitive char class won't be initialized by
300 // InitializePrimitiveClass until line 459, but strings (and
301 // internal char arrays) will be allocated before that and the
302 // component size, which is computed from the primitive type, needs
303 // to be set here.
304 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700305
Ian Rogers23435d02012-09-24 11:23:12 -0700306 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700307 Handle<mirror::Class> char_array_class(hs.NewHandle(
308 AllocClass(self, java_lang_Class.Get(),
309 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700310 char_array_class->SetComponentType(char_class.Get());
311 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700312
Ian Rogers23435d02012-09-24 11:23:12 -0700313 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700314 Handle<mirror::Class> java_lang_String(hs.NewHandle(
315 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700316 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700317 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700318 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400319
Fred Shih4ee7a662014-07-11 09:59:27 -0700320 // Setup Reference.
321 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
322 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
323 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
324 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
325 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
326
Ian Rogers23435d02012-09-24 11:23:12 -0700327 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700328 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
329 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
330 kClassRootsMax));
331 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700332 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
333 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
334 SetClassRoot(kClassArrayClass, class_array_class.Get());
335 SetClassRoot(kObjectArrayClass, object_array_class.Get());
336 SetClassRoot(kCharArrayClass, char_array_class.Get());
337 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700338 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700339
340 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700341 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
342 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
343 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
344 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
345 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
346 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
347 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
348 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349
Ian Rogers23435d02012-09-24 11:23:12 -0700350 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700351 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700352
Ian Rogers23435d02012-09-24 11:23:12 -0700353 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700354 Handle<mirror::Class> int_array_class(hs.NewHandle(
355 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700357 mirror::IntArray::SetArrayClass(int_array_class.Get());
358 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700360 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700361
Ian Rogers52813c92012-10-11 11:50:38 -0700362 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700363 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
364 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700365 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700366 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700367 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368
Brian Carlstromf3632832014-05-20 15:36:53 -0700369 // Constructor, Field, Method, and AbstractMethod are necessary so
370 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700371 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
372 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700373 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700374 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700375 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700376 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700377 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700379 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
380 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700381 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800382 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700383 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700384 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700385 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700386
387 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700388 Handle<mirror::Class> object_array_string(hs.NewHandle(
389 AllocClass(self, java_lang_Class.Get(),
390 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700391 object_array_string->SetComponentType(java_lang_String.Get());
392 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700393
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700394 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
395 AllocClass(self, java_lang_Class.Get(),
396 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700397 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
398 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700399
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700400 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
401 AllocClass(self, java_lang_Class.Get(),
402 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700403 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
404 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700405
Ian Rogers23435d02012-09-24 11:23:12 -0700406 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
407 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
408 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700409 CHECK_NE(0U, boot_class_path.size());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800410 for (const DexFile* dex_file : boot_class_path) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700411 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700412 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700413 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414
415 // now we can use FindSystemClass
416
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700417 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700418 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
419 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700420
Jeff Hao88474b42013-10-23 16:24:40 -0700421 // Create runtime resolution and imt conflict methods. Also setup the default imt.
422 Runtime* runtime = Runtime::Current();
423 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
424 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700425 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700426 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
427
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700428 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
429 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700430 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700431 if (!runtime->IsCompiler()) {
432 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700433 quick_resolution_trampoline_ = GetQuickResolutionStub();
434 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
435 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700436 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700437
Mathieu Chartier66f19252012-09-18 08:57:04 -0700438 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700439 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800440 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700441 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700442 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700443 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800444 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700445 std::ostringstream os1, os2;
446 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
447 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
448 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
449 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700450 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800451 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700452 CHECK_EQ(java_lang_String.Get(), String_class);
453 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700454 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455
Ian Rogers23435d02012-09-24 11:23:12 -0700456 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800457 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800458 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459
Ian Rogers98379392014-02-24 16:53:16 -0800460 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800461 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700462
Ian Rogers98379392014-02-24 16:53:16 -0800463 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700464 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700465
Ian Rogers98379392014-02-24 16:53:16 -0800466 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800467 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700468
Ian Rogers98379392014-02-24 16:53:16 -0800469 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700470 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700471
Ian Rogers98379392014-02-24 16:53:16 -0800472 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800473 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700474
Ian Rogers98379392014-02-24 16:53:16 -0800475 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800476 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700477
Ian Rogers98379392014-02-24 16:53:16 -0800478 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800479 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700480
Ian Rogers98379392014-02-24 16:53:16 -0800481 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700482 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700483
Ian Rogers98379392014-02-24 16:53:16 -0800484 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700485 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700486
Ian Rogers23435d02012-09-24 11:23:12 -0700487 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800488 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700489 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800490 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700491 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700492 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
493 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700494 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700495 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700496 array_iftable->SetInterface(0, java_lang_Cloneable);
497 array_iftable->SetInterface(1, java_io_Serializable);
498 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700499
Ian Rogers23435d02012-09-24 11:23:12 -0700500 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700501 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
502 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
503 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
504 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700505 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700506 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800507 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700508 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700509
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700510 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800511 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700512 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700513
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700514 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800515 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700516 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700517
Brian Carlstromf3632832014-05-20 15:36:53 -0700518 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700519 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700520 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700521
Brian Carlstromea46f952013-07-30 01:26:50 -0700522 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700523 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700524 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700525
Brian Carlstromea46f952013-07-30 01:26:50 -0700526 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700527 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700528 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700529
Ian Rogers23435d02012-09-24 11:23:12 -0700530 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700531
Ian Rogers23435d02012-09-24 11:23:12 -0700532 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800533 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700534 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
535
Brian Carlstrom1f870082011-08-23 16:02:11 -0700536 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700537 // finish initializing Reference class
538 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
539 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
540 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
541 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
542 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700543 mirror::Class* java_lang_ref_FinalizerReference =
544 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700545 java_lang_ref_FinalizerReference->SetAccessFlags(
546 java_lang_ref_FinalizerReference->GetAccessFlags() |
547 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700548 mirror::Class* java_lang_ref_PhantomReference =
549 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700550 java_lang_ref_PhantomReference->SetAccessFlags(
551 java_lang_ref_PhantomReference->GetAccessFlags() |
552 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700553 mirror::Class* java_lang_ref_SoftReference =
554 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700555 java_lang_ref_SoftReference->SetAccessFlags(
556 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700557 mirror::Class* java_lang_ref_WeakReference =
558 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 java_lang_ref_WeakReference->SetAccessFlags(
560 java_lang_ref_WeakReference->GetAccessFlags() |
561 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700562
Ian Rogers23435d02012-09-24 11:23:12 -0700563 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800564 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700565 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700566 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
567
jeffhao8cd6dda2012-02-22 10:15:34 -0800568 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700569 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800570 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800571 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700572 SetClassRoot(kJavaLangClassNotFoundException,
573 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800574 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700575 SetClassRoot(kJavaLangStackTraceElementArrayClass,
576 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800577 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700578
Ian Rogers98379392014-02-24 16:53:16 -0800579 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700580
Brian Carlstroma004aa92012-02-08 18:05:09 -0800581 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700582}
583
Ian Rogers98379392014-02-24 16:53:16 -0800584void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800585 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700586
587 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700588 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700589 // as the types of the field can't be resolved prior to the runtime being
590 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800591 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700592 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800593 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800594
Brian Carlstromea46f952013-07-30 01:26:50 -0700595 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700596 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
597 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700598
Brian Carlstromea46f952013-07-30 01:26:50 -0700599 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700600 CHECK_STREQ(queue->GetName(), "queue");
601 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700602
Brian Carlstromea46f952013-07-30 01:26:50 -0700603 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700604 CHECK_STREQ(queueNext->GetName(), "queueNext");
605 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700606
Brian Carlstromea46f952013-07-30 01:26:50 -0700607 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700608 CHECK_STREQ(referent->GetName(), "referent");
609 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700610
Brian Carlstromea46f952013-07-30 01:26:50 -0700611 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700612 CHECK_STREQ(zombie->GetName(), "zombie");
613 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700614
Brian Carlstroma663ea52011-08-19 23:33:41 -0700615 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700616 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700617 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800618 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700619 CHECK(klass != nullptr);
620 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700621 // note SetClassRoot does additional validation.
622 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700623 }
624
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700625 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700626
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700627 // disable the slow paths in FindClass and CreatePrimitiveClass now
628 // that Object, Class, and Object[] are setup
629 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700630
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800631 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700632}
633
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700634void ClassLinker::RunRootClinits() {
635 Thread* self = Thread::Current();
636 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800637 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700638 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700639 StackHandleScope<1> hs(self);
640 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700641 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700642 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700643 }
644 }
645}
646
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700647bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800648 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000649 const char* oat_cache_filename,
650 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700651 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700652 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800653
Ian Rogers1d54e732013-05-02 21:10:01 -0700654 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800655 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700656 if (heap->GetImageSpace() == nullptr) {
657 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
658 // out of space anyway it might not matter.
659 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
660 "without an image.", dex_filename);
661 return false;
662 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700663 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800664
Brian Carlstrom6449c622014-02-10 23:48:36 -0800665 std::string dex_file_option("--dex-file=");
666 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800667
Brian Carlstrom6449c622014-02-10 23:48:36 -0800668 std::string oat_fd_option("--oat-fd=");
669 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800670
Brian Carlstrom6449c622014-02-10 23:48:36 -0800671 std::string oat_location_option("--oat-location=");
672 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800673
Brian Carlstrom6449c622014-02-10 23:48:36 -0800674 std::vector<std::string> argv;
675 argv.push_back(dex2oat);
676 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800677 argv.push_back("-classpath");
678 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800679 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800680
Ian Rogers8afeb852014-04-02 14:55:49 -0700681 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800682
Jeff Hao4a200f52014-04-01 14:58:49 -0700683 if (!Runtime::Current()->IsVerificationEnabled()) {
684 argv.push_back("--compiler-filter=verify-none");
685 }
686
Alex Light6e183f22014-07-18 14:57:04 -0700687 if (Runtime::Current()->MustRelocateIfPossible()) {
688 argv.push_back("--runtime-arg");
689 argv.push_back("-Xrelocate");
690 } else {
691 argv.push_back("--runtime-arg");
692 argv.push_back("-Xnorelocate");
693 }
694
Brian Carlstrom6449c622014-02-10 23:48:36 -0800695 if (!kIsTargetBuild) {
696 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700697 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700698
Brian Carlstrom6449c622014-02-10 23:48:36 -0800699 argv.push_back(boot_image_option);
700 argv.push_back(dex_file_option);
701 argv.push_back(oat_fd_option);
702 argv.push_back(oat_location_option);
703 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800704 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800705 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700706 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800707
Andreas Gampea696c0a2014-12-10 20:51:45 -0800708 if (!Exec(argv, error_msg)) {
709 // Manually delete the file. Ensures there is no garbage left over if the process unexpectedly
710 // died. Ignore unlink failure, propagate the original error.
711 TEMP_FAILURE_RETRY(unlink(oat_cache_filename));
712 return false;
713 }
714
715 return true;
jeffhao262bf462011-10-20 18:36:32 -0700716}
717
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700718const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700719 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800720 if (kIsDebugBuild) {
721 for (size_t i = 0; i < oat_files_.size(); ++i) {
722 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700723 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800724 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700725 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
726 oat_files_.push_back(oat_file);
727 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800728}
729
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700730OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
731 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700732 OatFile* oat_file = space->ReleaseOatFile();
733 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700734 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700735 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700736}
737
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100738const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800739 const char* dex_location = dex_file.GetLocation().c_str();
740 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100741 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800742}
743
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100744const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
745 const char* dex_location,
746 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700747 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100748 for (const OatFile* oat_file : oat_files_) {
749 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700750
751 if (oat_location != nullptr) {
752 if (oat_file->GetLocation() != oat_location) {
753 continue;
754 }
755 }
756
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700757 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800758 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700759 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100760 if (oat_dex_file != nullptr) {
761 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800762 }
763 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100764 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800765}
766
Calin Juravle621962a2014-09-02 15:53:55 +0100767
768// Loads all multi dex files from the given oat file returning true on success.
769//
770// Parameters:
771// oat_file - the oat file to load from
772// dex_location - the dex location used to generate the oat file
773// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
774// generated - whether or not the oat_file existed before or was just (re)generated
775// error_msgs - any error messages will be appended here
776// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
777static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
778 const char* dex_location,
779 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700780 bool generated,
781 std::vector<std::string>* error_msgs,
782 std::vector<const DexFile*>* dex_files) {
783 if (oat_file == nullptr) {
784 return false;
785 }
786
787 size_t old_size = dex_files->size(); // To rollback on error.
788
789 bool success = true;
790 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100791 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700792 const char* next_name = next_name_str.c_str();
793
Calin Juravle621962a2014-09-02 15:53:55 +0100794 uint32_t next_location_checksum;
795 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700796 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100797 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
798 // When i=0 the multidex name should be the same as the location name. We already have the
799 // checksum it so we don't need to recompute it.
800 if (dex_location_checksum == nullptr) {
801 next_location_checksum_pointer = nullptr;
802 } else {
803 next_location_checksum = *dex_location_checksum;
804 }
805 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700806 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100807 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700808 }
809
810 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
811
812 if (oat_dex_file == nullptr) {
813 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700814 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100815 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700816 oat_file->GetLocation().c_str());
817 error_msgs->push_back(error_msg);
818 }
819 break; // Not found, done.
820 }
821
822 // Checksum test. Test must succeed when generated.
823 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100824 if (next_location_checksum_pointer != nullptr) {
825 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700826 }
827
828 if (success) {
829 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
830 if (dex_file == nullptr) {
831 success = false;
832 error_msgs->push_back(error_msg);
833 } else {
834 dex_files->push_back(dex_file);
835 }
836 }
837
838 // When we generated the file, we expect success, or something is terribly wrong.
839 CHECK_EQ(false, generated && !success)
840 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100841 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700842 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
843 }
844
845 if (dex_files->size() == old_size) {
846 success = false; // We did not even find classes.dex
847 }
848
849 if (success) {
850 return true;
851 } else {
852 // Free all the dex files we have loaded.
853 auto it = dex_files->begin() + old_size;
854 auto it_end = dex_files->end();
855 for (; it != it_end; it++) {
856 delete *it;
857 }
858 dex_files->erase(dex_files->begin() + old_size, it_end);
859
860 return false;
861 }
862}
863
864// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
865// complicates the loading process, as we should not use an iterative loading process, because that
866// would register the oat file and dex files that come before the broken one. Instead, check all
867// multidex ahead of time.
868bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
869 std::vector<std::string>* error_msgs,
870 std::vector<const DexFile*>* dex_files) {
871 // 1) Check whether we have an open oat file.
872 // This requires a dex checksum, use the "primary" one.
873 uint32_t dex_location_checksum;
874 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
875 bool have_checksum = true;
876 std::string checksum_error_msg;
877 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100878 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700879 dex_location_checksum_pointer = nullptr;
880 have_checksum = false;
881 }
882
883 bool needs_registering = false;
884
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100885 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
886 dex_location_checksum_pointer);
887 std::unique_ptr<const OatFile> open_oat_file(
888 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700889
890 // 2) If we do not have an open one, maybe there's one on disk already.
891
892 // In case the oat file is not open, we play a locking game here so
893 // that if two different processes race to load and register or generate
894 // (or worse, one tries to open a partial generated file) we will be okay.
895 // This is actually common with apps that use DexClassLoader to work
896 // around the dex method reference limit and that have a background
897 // service running in a separate process.
898 ScopedFlock scoped_flock;
899
900 if (open_oat_file.get() == nullptr) {
901 if (oat_location != nullptr) {
902 // Can only do this if we have a checksum, else error.
903 if (!have_checksum) {
904 error_msgs->push_back(checksum_error_msg);
905 return false;
906 }
907
908 std::string error_msg;
909
910 // We are loading or creating one in the future. Time to set up the file lock.
911 if (!scoped_flock.Init(oat_location, &error_msg)) {
912 error_msgs->push_back(error_msg);
913 return false;
914 }
915
Alex Lighta59dd802014-07-02 16:28:08 -0700916 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700917 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
918 oat_location, &error_msg));
919
920 if (open_oat_file.get() == nullptr) {
921 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
922 dex_location, oat_location, error_msg.c_str());
923 VLOG(class_linker) << compound_msg;
924 error_msgs->push_back(compound_msg);
925 }
926 } else {
927 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100928 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700929 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
930 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100931 kRuntimeISA, error_msgs,
932 &obsolete_file_cleanup_failed));
933 // There's no point in going forward and eventually try to regenerate the
934 // file if we couldn't remove the obsolete one. Mostly likely we will fail
935 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100936 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
937 if (obsolete_file_cleanup_failed) {
938 return false;
939 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700940 }
941 needs_registering = true;
942 }
943
944 // 3) If we have an oat file, check all contained multidex files for our dex_location.
945 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100946 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
947 dex_location_checksum_pointer,
948 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700949 if (success) {
950 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
951 if (needs_registering) {
952 // We opened the oat file, so we must register it.
953 RegisterOatFile(oat_file);
954 }
Alex Light9dcc4572014-08-14 14:16:26 -0700955 // If the file isn't executable we failed patchoat but did manage to get the dex files.
956 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700957 } else {
958 if (needs_registering) {
959 // We opened it, delete it.
960 open_oat_file.reset();
961 } else {
962 open_oat_file.release(); // Do not delete open oat files.
963 }
964 }
965
966 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
967
968 // Need a checksum, fail else.
969 if (!have_checksum) {
970 error_msgs->push_back(checksum_error_msg);
971 return false;
972 }
973
974 // Look in cache location if no oat_location is given.
975 std::string cache_location;
976 if (oat_location == nullptr) {
977 // Use the dalvik cache.
978 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
979 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
980 oat_location = cache_location.c_str();
981 }
982
Alex Light64ad14d2014-08-19 14:23:13 -0700983 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700984 // Definitely need to lock now.
985 if (!scoped_flock.HasFile()) {
986 std::string error_msg;
987 if (!scoped_flock.Init(oat_location, &error_msg)) {
988 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700989 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700990 }
991 }
992
Alex Light64ad14d2014-08-19 14:23:13 -0700993 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +0100994 // Create the oat file.
995 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
996 oat_location, error_msgs));
997 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700998
999 // Failed, bail.
1000 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001001 std::string error_msg;
1002 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1003 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1004 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001005 return false;
1006 }
1007
1008 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001009 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1010 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001011 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001012 if (success) {
1013 RegisterOatFile(open_oat_file.release());
1014 return true;
1015 } else {
1016 return false;
1017 }
1018}
1019
1020const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1021 uint32_t dex_location_checksum,
1022 const char* oat_location,
1023 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001024 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001025 !Runtime::Current()->IsCompiler(),
1026 error_msg));
1027 if (oat_file.get() == nullptr) {
1028 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1029 error_msg->c_str());
1030 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001031 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001032 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001033 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1034 if (image_space != nullptr) {
1035 const ImageHeader& image_header = image_space->GetImageHeader();
1036 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1037 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1038 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1039 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1040 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1041 actual_image_oat_checksum);
1042 return nullptr;
1043 }
1044
1045 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1046 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1047 if (expected_image_oat_offset != actual_image_oat_offset) {
1048 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1049 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1050 actual_image_oat_offset);
1051 return nullptr;
1052 }
1053 int32_t expected_patch_delta = image_header.GetPatchDelta();
1054 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1055 if (expected_patch_delta != actual_patch_delta) {
1056 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1057 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1058 return nullptr;
1059 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001060 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001061
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001062 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1063 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001064 if (oat_dex_file == nullptr) {
1065 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1066 dex_location);
1067 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001068 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001069 uint32_t expected_dex_checksum = dex_location_checksum;
1070 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1071 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001072 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1073 "found 0x%x", oat_location, expected_dex_checksum,
1074 actual_dex_checksum);
1075 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001076 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001077 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1078 if (dex_file.get() != nullptr) {
1079 return oat_file.release();
1080 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001081 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001082 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001083}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001084
Andreas Gampe833a4852014-05-21 18:46:59 -07001085const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1086 int fd, const char* oat_location,
1087 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001088 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001089 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001090 std::string error_msg;
1091 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001092 CHECK(!error_msg.empty());
1093 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001094 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001095 }
Igor Murashkin46774762014-10-22 11:37:02 -07001096 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001097 !Runtime::Current()->IsCompiler(),
1098 &error_msg));
1099 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001100 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1101 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001102 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001103 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001104 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001105
1106 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001107}
1108
Alex Light6e183f22014-07-18 14:57:04 -07001109bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1110 const InstructionSet instruction_set) {
1111 Runtime* runtime = Runtime::Current();
1112 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001113 if (image_space == nullptr) {
1114 return false;
1115 }
Alex Light6e183f22014-07-18 14:57:04 -07001116 uint32_t image_oat_checksum = 0;
1117 if (instruction_set == kRuntimeISA) {
1118 const ImageHeader& image_header = image_space->GetImageHeader();
1119 image_oat_checksum = image_header.GetOatChecksum();
1120 } else {
1121 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1122 image_space->GetImageLocation().c_str(), instruction_set));
1123 image_oat_checksum = image_header->GetOatChecksum();
1124 }
1125 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1126}
1127
1128bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1129 const InstructionSet instruction_set,
1130 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001131 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001132 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001133 if (image_space == nullptr) {
1134 *error_msg = "No image space for verification against";
1135 return false;
1136 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001137
1138 // If the requested instruction set is the same as the current runtime,
1139 // we can use the checksums directly. If it isn't, we'll have to read the
1140 // image header from the image for the right instruction set.
1141 uint32_t image_oat_checksum = 0;
1142 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001143 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001144 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001145 const ImageHeader& image_header = image_space->GetImageHeader();
1146 image_oat_checksum = image_header.GetOatChecksum();
1147 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001148 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001149 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001150 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001151 image_space->GetImageLocation().c_str(), instruction_set));
1152 image_oat_checksum = image_header->GetOatChecksum();
1153 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001154 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001155 }
1156 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001157 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1158
1159 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1160 if (!oat_file->IsPic()) {
1161 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1162 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1163 }
Alex Light6e183f22014-07-18 14:57:04 -07001164 if (!ret) {
1165 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1166 oat_file->GetLocation().c_str(),
1167 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1168 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1169 oat_file->GetOatHeader().GetImagePatchDelta(),
1170 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1171 }
1172 return ret;
1173}
1174
1175bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1176 const char* dex_location,
1177 uint32_t dex_location_checksum,
1178 const InstructionSet instruction_set,
1179 std::string* error_msg) {
1180 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1181 return false;
1182 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001183
Brian Carlstromf3632832014-05-20 15:36:53 -07001184 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1185 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001186 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001187 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1188 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001189 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001190 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001191 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001192 oat_dex_file_in->GetDexFileLocation().c_str(),
1193 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001194 }
1195 return false;
1196 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001197
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001198 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001199 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001200}
1201
Alex Lighta59dd802014-07-02 16:28:08 -07001202bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1203 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001204 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001205 std::string* error_msg) {
1206 CHECK(oat_file != nullptr);
1207 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001208 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001209 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001210 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1211 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1212 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001213 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001214 if (oat_dex_file == nullptr) {
1215 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001216 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001217 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001218 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001219 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001220 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001221 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001222 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001223 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001224 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001225 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001226 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001227 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001228 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001229 }
Alex Lighta59dd802014-07-02 16:28:08 -07001230 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001231}
1232
Andreas Gampe833a4852014-05-21 18:46:59 -07001233const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001234 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001235 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001236 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001237 std::vector<std::string>* error_msgs,
1238 bool* obsolete_file_cleanup_failed) {
1239 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001240 bool already_opened = false;
1241 std::string dex_location_str(dex_location);
1242 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1243 &already_opened,
1244 obsolete_file_cleanup_failed,
1245 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001246 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001247 if (oat_file.get() == nullptr) {
1248 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1249 dex_location));
1250 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001251 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001252 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1253 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001254 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1255 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001256 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001257 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001258 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001259 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001260 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1261 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1262 "dex location '%s'. Image checksum incorrect.",
1263 oat_file->GetLocation().c_str(), dex_location));
1264 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001265 } else {
1266 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001267 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001268}
1269
Brian Carlstromae826982011-11-09 01:33:42 -08001270const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001271 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001272 for (size_t i = 0; i < oat_files_.size(); i++) {
1273 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001274 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001275 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001276 return oat_file;
1277 }
1278 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001279 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001280}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001281
Alex Lighta59dd802014-07-02 16:28:08 -07001282const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1283 InstructionSet isa,
1284 bool *already_opened,
1285 bool *obsolete_file_cleanup_failed,
1286 std::vector<std::string>* error_msgs) {
1287 // Find out if we've already opened the file
1288 const OatFile* ret = nullptr;
1289 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1290 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1291 if (ret != nullptr) {
1292 *already_opened = true;
1293 return ret;
1294 }
1295
1296 std::string dalvik_cache;
1297 bool have_android_data = false;
1298 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001299 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001300 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001301 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001302 std::string cache_filename;
1303 if (have_dalvik_cache) {
1304 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1305 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1306 if (ret != nullptr) {
1307 *already_opened = true;
1308 return ret;
1309 }
1310 } else {
1311 // If we need to relocate we should just place odex back where it started.
1312 cache_filename = odex_filename;
1313 }
1314
1315 ret = nullptr;
1316
1317 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1318 //
1319 // Now we do the following:
1320 // 1) Try and open the odex version
1321 // 2) If present, checksum-verified & relocated correctly return it
1322 // 3) Close the odex version to free up its address space.
1323 // 4) Try and open the cache version
1324 // 5) If present, checksum-verified & relocated correctly return it
1325 // 6) Close the cache version to free up its address space.
1326 // 7) If we should relocate:
1327 // a) If we have opened and checksum-verified the odex version relocate it to
1328 // 'cache_filename' and return it
1329 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1330 // it. This should not happen often (I think only the run-test's will hit this case).
1331 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1332 // this point.
1333 // 9) Return nullptr
1334
1335 *already_opened = false;
1336 const Runtime* runtime = Runtime::Current();
1337 CHECK(runtime != nullptr);
1338 bool executable = !runtime->IsCompiler();
1339
1340 std::string odex_error_msg;
1341 bool should_patch_system = false;
1342 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001343 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001344 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001345 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001346 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001347 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001348 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001349 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001350 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001351 &odex_checksum_verified,
1352 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001353 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001354 } else {
1355 if (odex_checksum_verified) {
1356 // We can just relocate
1357 should_patch_system = true;
1358 odex_error_msg = "Image Patches are incorrect";
1359 }
1360 if (odex_oat_file.get() != nullptr) {
1361 have_system_odex = true;
1362 }
Alex Lighta59dd802014-07-02 16:28:08 -07001363 }
1364 }
1365
Alex Lighta59dd802014-07-02 16:28:08 -07001366 std::string cache_error_msg;
1367 bool should_patch_cache = false;
1368 bool cache_checksum_verified = false;
1369 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001370 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001371 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001372 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001373 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001374 &cache_checksum_verified,
1375 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001376 return cache_oat_file.release();
1377 } else if (cache_checksum_verified) {
1378 // We can just relocate
1379 should_patch_cache = true;
1380 cache_error_msg = "Image Patches are incorrect";
1381 }
1382 } else if (have_android_data) {
1383 // dalvik_cache does not exist but android data does. This means we should be able to create
1384 // it, so we should try.
1385 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1386 }
1387
1388 ret = nullptr;
1389 std::string error_msg;
1390 if (runtime->CanRelocate()) {
1391 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001392 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1393 if (space != nullptr) {
1394 const std::string& image_location = space->GetImageLocation();
1395 if (odex_checksum_verified && should_patch_system) {
1396 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1397 } else if (cache_checksum_verified && should_patch_cache) {
1398 CHECK(have_dalvik_cache);
1399 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1400 }
Alex Light84d76052014-08-22 17:49:35 -07001401 } else if (have_system_odex) {
1402 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001403 }
1404 }
1405 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1406 // implicitly: were able to fine where the cached version is but we were unable to use it,
1407 // either as a destination for relocation or to open a file. We should delete it if it is
1408 // there.
1409 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1410 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1411 "searching for dex file %s: %s",
1412 cache_filename.c_str(), dex_location.c_str(),
1413 strerror(errno));
1414 error_msgs->push_back(rm_error_msg);
1415 VLOG(class_linker) << rm_error_msg;
1416 // Let the caller know that we couldn't remove the obsolete file.
1417 // This is a good indication that further writes may fail as well.
1418 *obsolete_file_cleanup_failed = true;
1419 }
1420 }
1421 if (ret == nullptr) {
1422 VLOG(class_linker) << error_msg;
1423 error_msgs->push_back(error_msg);
1424 std::string relocation_msg;
1425 if (runtime->CanRelocate()) {
1426 relocation_msg = StringPrintf(" and relocation failed");
1427 }
1428 if (have_dalvik_cache && cache_checksum_verified) {
1429 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1430 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1431 cache_filename.c_str(), cache_error_msg.c_str(),
1432 relocation_msg.c_str());
1433 } else {
1434 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1435 "dalvik_cache availible)%s.", odex_filename.c_str(),
1436 odex_error_msg.c_str(), relocation_msg.c_str());
1437 }
1438 VLOG(class_linker) << error_msg;
1439 error_msgs->push_back(error_msg);
1440 }
1441 return ret;
1442}
1443
Alex Light9dcc4572014-08-14 14:16:26 -07001444const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1445 InstructionSet isa,
1446 std::string* error_msg) {
1447 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001448 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001449 if (output.get() == nullptr) {
1450 return nullptr;
1451 }
Alex Light84d76052014-08-22 17:49:35 -07001452 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1453 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001454 return output.release();
1455 } else {
1456 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1457 oat_path.c_str());
1458 return nullptr;
1459 }
1460}
1461
Alex Lighta59dd802014-07-02 16:28:08 -07001462const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1463 const std::string& output_oat,
1464 const std::string& image_location,
1465 InstructionSet isa,
1466 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001467 Runtime* runtime = Runtime::Current();
1468 DCHECK(runtime != nullptr);
1469 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001470 // We don't have an image space so there is no point in trying to patchoat.
1471 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1472 << "running without an image. Attempting to use oat file for interpretation.";
1473 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1474 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001475 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001476 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1477 // input_oat but make sure we only do interpretation on it's dex files.
1478 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1479 << "disabled. Attempting to use oat file for interpretation";
1480 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1481 }
Alex Lighta59dd802014-07-02 16:28:08 -07001482 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001483 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001484
1485 std::string isa_arg("--instruction-set=");
1486 isa_arg += GetInstructionSetString(isa);
1487 std::string input_oat_filename_arg("--input-oat-file=");
1488 input_oat_filename_arg += input_oat;
1489 std::string output_oat_filename_arg("--output-oat-file=");
1490 output_oat_filename_arg += output_oat;
1491 std::string patched_image_arg("--patched-image-location=");
1492 patched_image_arg += image_location;
1493
1494 std::vector<std::string> argv;
1495 argv.push_back(patchoat);
1496 argv.push_back(isa_arg);
1497 argv.push_back(input_oat_filename_arg);
1498 argv.push_back(output_oat_filename_arg);
1499 argv.push_back(patched_image_arg);
1500
1501 std::string command_line(Join(argv, ' '));
1502 LOG(INFO) << "Relocate Oat File: " << command_line;
1503 bool success = Exec(argv, error_msg);
1504 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001505 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001506 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001507 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001508 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1509 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001510 return output.release();
1511 } else if (output.get() != nullptr) {
1512 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1513 "but output file '%s' failed verifcation: %s",
1514 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1515 } else {
1516 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1517 "but was unable to open output file '%s': %s",
1518 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1519 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001520 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001521 // patchoat failed which means we probably don't have enough room to place the output oat file,
1522 // instead of failing we should just run the interpreter from the dex files in the input oat.
1523 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1524 << "for interpretation. patchoat failure was: " << *error_msg;
1525 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001526 } else {
1527 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1528 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1529 error_msg->c_str());
1530 }
1531 return nullptr;
1532}
1533
Andreas Gampe7ba64962014-10-23 11:37:40 -07001534bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001535 bool* checksum_verified,
1536 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001537 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001538 if (image_space == nullptr) {
1539 *error_msg = "No image space present";
1540 return false;
1541 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001542 uint32_t real_image_checksum;
1543 void* real_image_oat_offset;
1544 int32_t real_patch_delta;
1545 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001546 const ImageHeader& image_header = image_space->GetImageHeader();
1547 real_image_checksum = image_header.GetOatChecksum();
1548 real_image_oat_offset = image_header.GetOatDataBegin();
1549 real_patch_delta = image_header.GetPatchDelta();
1550 } else {
1551 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1552 image_space->GetImageLocation().c_str(), isa));
1553 real_image_checksum = image_header->GetOatChecksum();
1554 real_image_oat_offset = image_header->GetOatDataBegin();
1555 real_patch_delta = image_header->GetPatchDelta();
1556 }
1557
1558 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001559 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001560
1561 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1562 *checksum_verified = oat_image_checksum == real_image_checksum;
1563 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001564 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1565 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001566 }
1567
Andreas Gampe7ba64962014-10-23 11:37:40 -07001568 bool offset_verified;
1569 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001570
Andreas Gampe7ba64962014-10-23 11:37:40 -07001571 if (!oat_file->IsPic()) {
1572 // If an oat file is not PIC, we need to check that the image is at the expected location and
1573 // patched in the same way.
1574 void* oat_image_oat_offset =
1575 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1576 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1577 if (!offset_verified) {
1578 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1579 real_image_oat_offset, oat_image_oat_offset);
1580 }
1581
1582 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1583 patch_delta_verified = oat_patch_delta == real_patch_delta;
1584 if (!patch_delta_verified) {
1585 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1586 "received 0x%x)", real_patch_delta, oat_patch_delta);
1587 }
1588 } else {
1589 // If an oat file is PIC, we ignore offset and patching delta.
1590 offset_verified = true;
1591 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001592 }
1593
1594 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001595 if (!ret) {
1596 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001597 }
1598 return ret;
1599}
1600
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001601const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1602 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001603 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001604 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001605 return oat_file;
1606 }
1607
Igor Murashkin46774762014-10-22 11:37:02 -07001608 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001609 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001610}
1611
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001612void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001613 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001614 DCHECK(obj != nullptr);
1615 DCHECK(class_linker != nullptr);
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001616 size_t pointer_size = class_linker->image_pointer_size_;
Ian Rogers848871b2013-08-05 10:56:33 -07001617
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001618 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001619 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001620 if (!method->IsNative()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001621 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001622 if (method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001623 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1624 pointer_size);
1625 method->SetEntryPointFromPortableCompiledCodePtrSize(GetPortableToInterpreterBridge(),
1626 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001627 }
1628 }
1629 }
1630}
1631
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001632void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001633 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001634 CHECK(!init_done_);
1635
Mathieu Chartier590fee92013-09-13 13:46:47 -07001636 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001637 gc::Heap* heap = Runtime::Current()->GetHeap();
1638 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001639 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001640 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001641 OatFile& oat_file = GetImageOatFile(space);
1642 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1643 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001644 const char* image_file_location = oat_file.GetOatHeader().
1645 GetStoreValueByKey(OatHeader::kImageLocationKey);
1646 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001647 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1648 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001649 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1650 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001651 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001652 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001653 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1654 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1655 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001656
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001657 StackHandleScope<1> hs(self);
1658 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1659 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1660 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001661 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001662
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001663 // Special case of setting up the String class early so that we can test arbitrary objects
1664 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001665 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001666
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001667 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001668 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001669 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001670 StackHandleScope<1> hs2(self);
1671 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001672 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001673 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1674 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001675 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001676 std::string error_msg;
1677 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001678 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001679 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001680 << " from within oat file " << oat_file.GetLocation()
1681 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001682 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001683 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001684
1685 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1686
1687 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001688 }
1689
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001690 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1691 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001692 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001693 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
1694 if (!Runtime::Current()->IsCompiler()) {
1695 // Compiler supports having an image with a different pointer size than the runtime. This
1696 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1697 // also use 32 bit dex2oat on a system with 64 bit apps.
1698 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1699 << sizeof(void*);
1700 }
1701 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1702 image_pointer_size_ = 4;
1703 } else {
1704 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1705 image_pointer_size_ = 8;
1706 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001707
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001708 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001709 Runtime* runtime = Runtime::Current();
1710 if (!runtime->IsCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001711 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001712 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001713 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001714
1715 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001716 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001717 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001718
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001719 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001720 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001721 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001722 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001723 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001724 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001725 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1726 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1727 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1728 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1729 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1730 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1731 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1732 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1733 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1734 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001735
Ian Rogers98379392014-02-24 16:53:16 -08001736 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001737
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001738 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001739}
1740
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001741void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1742 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1743 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001744 for (GcRoot<mirror::Class>& root : class_table_) {
1745 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1746 }
1747 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1748 root.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001749 }
1750 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001751 for (auto& root : new_class_roots_) {
1752 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
1753 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1754 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001755 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001756 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1757 // corresponding object. This is slow, but luckily for us, this may only happen with a
1758 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001759 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
1760 class_table_.Erase(it);
1761 class_table_.Insert(GcRoot<mirror::Class>(new_ref));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001762 }
1763 }
1764 }
1765 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1766 new_class_roots_.clear();
1767 }
1768 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1769 log_new_class_table_roots_ = true;
1770 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1771 log_new_class_table_roots_ = false;
1772 }
1773 // We deliberately ignore the class roots in the image since we
1774 // handle image roots by using the MS/CMS rescanning of dirty cards.
1775}
1776
Brian Carlstroma663ea52011-08-19 23:33:41 -07001777// Keep in sync with InitCallback. Anything we visit, we need to
1778// reinit references to when reinitializing a ClassLinker from a
1779// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001780void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001781 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001782 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001783 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001784 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001785 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001786 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1787 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001788 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001789 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1790 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001791 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001792 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001793 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001794 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1795 new_dex_cache_roots_.clear();
1796 }
1797 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1798 log_new_dex_caches_roots_ = true;
1799 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1800 log_new_dex_caches_roots_ = false;
1801 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001802 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001803 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001804 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1805 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001806 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001807 if (!find_array_class_cache_[i].IsNull()) {
1808 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001809 }
1810 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001811}
1812
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001813void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1814 if (dex_cache_image_class_lookup_required_) {
1815 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001816 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001817 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001818 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001819 for (GcRoot<mirror::Class>& root : class_table_) {
1820 if (!visitor(root.Read(), arg)) {
1821 return;
1822 }
1823 }
1824 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1825 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001826 return;
1827 }
1828 }
1829}
1830
Ian Rogersdbf3be02014-08-29 15:40:08 -07001831static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001832 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001833 classes->insert(c);
1834 return true;
1835}
1836
Ian Rogersdbf3be02014-08-29 15:40:08 -07001837struct GetClassesVisitorArrayArg {
1838 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1839 int32_t index;
1840 bool success;
1841};
1842
1843static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1844 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1845 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1846 if (arg->index < (*arg->classes)->GetLength()) {
1847 (*arg->classes)->Set(arg->index, c);
1848 arg->index++;
1849 return true;
1850 } else {
1851 arg->success = false;
1852 return false;
1853 }
1854}
1855
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001856void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001857 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1858 // is avoiding duplicates.
1859 if (!kMovingClasses) {
1860 std::set<mirror::Class*> classes;
1861 VisitClasses(GetClassesVisitorSet, &classes);
1862 for (mirror::Class* klass : classes) {
1863 if (!visitor(klass, arg)) {
1864 return;
1865 }
1866 }
1867 } else {
1868 Thread* self = Thread::Current();
1869 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001870 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001871 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1872 GetClassesVisitorArrayArg local_arg;
1873 local_arg.classes = &classes;
1874 local_arg.success = false;
1875 // We size the array assuming classes won't be added to the class table during the visit.
1876 // If this assumption fails we iterate again.
1877 while (!local_arg.success) {
1878 size_t class_table_size;
1879 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001880 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001881 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001882 }
1883 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1884 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1885 classes.Assign(
1886 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1887 CHECK(classes.Get() != nullptr); // OOME.
1888 local_arg.index = 0;
1889 local_arg.success = true;
1890 VisitClasses(GetClassesVisitorArray, &local_arg);
1891 }
1892 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1893 // If the class table shrank during creation of the clases array we expect null elements. If
1894 // the class table grew then the loop repeats. If classes are created after the loop has
1895 // finished then we don't visit.
1896 mirror::Class* klass = classes->Get(i);
1897 if (klass != nullptr && !visitor(klass, arg)) {
1898 return;
1899 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001900 }
1901 }
1902}
1903
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001904ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001905 mirror::Class::ResetClass();
1906 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001907 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001908 mirror::ArtField::ResetClass();
1909 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001910 mirror::BooleanArray::ResetArrayClass();
1911 mirror::ByteArray::ResetArrayClass();
1912 mirror::CharArray::ResetArrayClass();
1913 mirror::DoubleArray::ResetArrayClass();
1914 mirror::FloatArray::ResetArrayClass();
1915 mirror::IntArray::ResetArrayClass();
1916 mirror::LongArray::ResetArrayClass();
1917 mirror::ShortArray::ResetArrayClass();
1918 mirror::Throwable::ResetClass();
1919 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001920 STLDeleteElements(&boot_class_path_);
1921 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001922}
1923
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001924mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001925 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001926 StackHandleScope<16> hs(self);
1927 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1928 Handle<mirror::DexCache> dex_cache(
1929 hs.NewHandle(down_cast<mirror::DexCache*>(
1930 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1931 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001932 if (dex_cache.Get() == nullptr) {
1933 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001934 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001935 Handle<mirror::String>
1936 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001937 if (location.Get() == nullptr) {
1938 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001939 }
Ian Rogers700a4022014-05-19 16:49:03 -07001940 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001941 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001942 if (strings.Get() == nullptr) {
1943 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001944 }
Ian Rogers700a4022014-05-19 16:49:03 -07001945 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001946 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001947 if (types.Get() == nullptr) {
1948 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001949 }
Ian Rogers700a4022014-05-19 16:49:03 -07001950 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001951 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001952 if (methods.Get() == nullptr) {
1953 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001954 }
Ian Rogers700a4022014-05-19 16:49:03 -07001955 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001956 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001957 if (fields.Get() == nullptr) {
1958 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001959 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001960 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1961 fields.Get());
1962 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001963}
1964
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001965mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001966 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001967 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001968 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001969 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001970 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001971 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1972 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001973 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001974 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001975 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001976 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001977 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001978}
1979
Ian Rogers6fac4472014-02-25 17:01:10 -08001980mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001981 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001982}
1983
Brian Carlstromea46f952013-07-30 01:26:50 -07001984mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001985 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001986 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001987}
1988
Brian Carlstromea46f952013-07-30 01:26:50 -07001989mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001990 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001991 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001992}
1993
Mathieu Chartier590fee92013-09-13 13:46:47 -07001994mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1995 Thread* self, size_t length) {
1996 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1997 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001998}
1999
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002000mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2001 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002002 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002003
2004 // For temporary classes we must wait for them to be retired.
2005 if (init_done_ && klass->IsTemp()) {
2006 CHECK(!klass->IsResolved());
2007 if (klass->IsErroneous()) {
2008 ThrowEarlierClassFailure(klass);
2009 return nullptr;
2010 }
2011 StackHandleScope<1> hs(self);
2012 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2013 ObjectLock<mirror::Class> lock(self, h_class);
2014 // Loop and wait for the resolving thread to retire this class.
2015 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2016 lock.WaitIgnoringInterrupts();
2017 }
2018 if (h_class->IsErroneous()) {
2019 ThrowEarlierClassFailure(h_class.Get());
2020 return nullptr;
2021 }
2022 CHECK(h_class->IsRetired());
2023 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002024 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2025 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002026 }
2027
Brian Carlstromaded5f72011-10-07 17:15:04 -07002028 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002029 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002030 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002031 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2032 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002033 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002034 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2035 ThrowClassCircularityError(h_class.Get());
2036 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002037 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002038 }
2039 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002040 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002041 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002042 }
2043 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002044
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002045 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002046 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002047 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002048 }
2049 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002050 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002051 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002052 return klass;
2053}
2054
Ian Rogers68b56852014-08-29 20:19:11 -07002055typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2056
2057// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002058ClassPathEntry FindInClassPath(const char* descriptor,
2059 size_t hash, const std::vector<const DexFile*>& class_path) {
2060 for (const DexFile* dex_file : class_path) {
2061 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002062 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002063 return ClassPathEntry(dex_file, dex_class_def);
2064 }
2065 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002066 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002067}
2068
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002069mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2070 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002071 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002072 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002073 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002074 if (class_loader->GetClass() !=
2075 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2076 class_loader->GetParent()->GetClass() !=
2077 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2078 return nullptr;
2079 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002080 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002081 // Check if this would be found in the parent boot class loader.
2082 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002083 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002084 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002085 // May return null if resolution on another thread fails.
2086 klass = EnsureResolved(self, descriptor, klass);
2087 } else {
2088 // May OOME.
2089 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2090 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002091 }
Ian Rogers32427292014-11-19 14:05:21 -08002092 if (klass == nullptr) {
2093 CHECK(self->IsExceptionPending()) << descriptor;
2094 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002095 }
Ian Rogers32427292014-11-19 14:05:21 -08002096 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002097 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002098 // Handle as if this is the child PathClassLoader.
2099 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002100 StackHandleScope<3> hs(self);
2101 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2102 // We need to get the DexPathList and loop through it.
2103 Handle<mirror::ArtField> cookie_field =
2104 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2105 Handle<mirror::ArtField> dex_file_field =
2106 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002107 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002108 mirror::Object* dex_path_list =
2109 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2110 GetObject(class_loader.Get());
2111 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2112 cookie_field.Get() != nullptr) {
2113 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2114 mirror::Object* dex_elements_obj =
2115 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2116 GetObject(dex_path_list);
2117 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2118 // at the mCookie which is a DexFile vector.
2119 if (dex_elements_obj != nullptr) {
2120 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2121 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2122 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2123 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2124 if (element == nullptr) {
2125 // Should never happen, fall back to java code to throw a NPE.
2126 break;
2127 }
2128 mirror::Object* dex_file = dex_file_field->GetObject(element);
2129 if (dex_file != nullptr) {
2130 const uint64_t cookie = cookie_field->GetLong(dex_file);
2131 auto* dex_files =
2132 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2133 if (dex_files == nullptr) {
2134 // This should never happen so log a warning.
2135 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2136 break;
2137 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002138 for (const DexFile* cp_dex_file : *dex_files) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002139 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002140 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002141 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002142 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2143 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002144 if (klass == nullptr) {
2145 CHECK(self->IsExceptionPending()) << descriptor;
2146 self->ClearException();
2147 return nullptr;
2148 }
2149 return klass;
2150 }
2151 }
2152 }
2153 }
2154 }
2155 }
Ian Rogers32427292014-11-19 14:05:21 -08002156 self->AssertNoPendingException();
2157 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002158 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002159}
2160
Ian Rogers98379392014-02-24 16:53:16 -08002161mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002162 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002163 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002164 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002165 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002166 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002167 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2168 // for primitive classes that aren't backed by dex files.
2169 return FindPrimitiveClass(descriptor[0]);
2170 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002171 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002172 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002173 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002174 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002175 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002176 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002177 // Class is not yet loaded.
2178 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002179 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002180 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002181 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002182 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002183 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002184 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002185 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002186 } else {
2187 // The boot class loader is searched ahead of the application class loader, failures are
2188 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2189 // trigger the chaining with a proper stack trace.
2190 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2191 self->SetException(ThrowLocation(), pre_allocated);
2192 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002193 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002194 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002195 // First try with the bootstrap class loader.
2196 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002197 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002198 if (klass != nullptr) {
2199 return EnsureResolved(self, descriptor, klass);
2200 }
2201 }
Ian Rogers63557452014-06-04 16:57:15 -07002202 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2203 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002204 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002205 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002206 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002207 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002208 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002209 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002210 const std::vector<const DexFile*>* class_path;
2211 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002212 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002213 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002214 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002215 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2216 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002217 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002218 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002219 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002220 } else {
2221 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2222 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2223 self->SetException(ThrowLocation(), pre_allocated);
2224 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002225 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002226 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002227 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002228 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2229 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002230 if (cp_klass != nullptr) {
2231 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002232 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002233 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002234 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002235 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002236 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002237 {
2238 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002239 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2240 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002241 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002242 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002243 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002244 }
Ian Rogers68b56852014-08-29 20:19:11 -07002245 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002246 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2247 WellKnownClasses::java_lang_ClassLoader_loadClass,
2248 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002249 }
Ian Rogers98379392014-02-24 16:53:16 -08002250 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002251 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002252 return nullptr;
2253 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002254 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002255 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002256 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002257 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002258 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002259 // success, return mirror::Class*
2260 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002261 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002262 }
Ian Rogers07140832014-09-30 15:43:59 -07002263 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002264}
2265
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002266mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002267 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002268 const DexFile& dex_file,
2269 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002270 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002271 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002272
Brian Carlstromaded5f72011-10-07 17:15:04 -07002273 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002274 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002275 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002276 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002277 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002278 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002279 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002280 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002281 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002282 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2283 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002284 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002285 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002286 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002287 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002288 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002289 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002290 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002291 }
2292
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002293 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002294 // Allocate a class with the status of not ready.
2295 // Interface object should get the right size here. Regular class will
2296 // figure out the right size later and be replaced with one of the right
2297 // size when the class becomes resolved.
2298 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002299 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002300 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002301 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002302 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002303 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002304 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002305 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002306 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002307 if (self->IsExceptionPending()) {
2308 // An exception occured during load, set status to erroneous while holding klass' lock in case
2309 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002310 if (!klass->IsErroneous()) {
2311 klass->SetStatus(mirror::Class::kStatusError, self);
2312 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002313 return nullptr;
2314 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002315 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002316
Mathieu Chartier590fee92013-09-13 13:46:47 -07002317 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002318 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002319 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002320 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2321 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002322 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002323 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002324
Brian Carlstromaded5f72011-10-07 17:15:04 -07002325 // Finish loading (if necessary) by finding parents
2326 CHECK(!klass->IsLoaded());
2327 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2328 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002329 if (!klass->IsErroneous()) {
2330 klass->SetStatus(mirror::Class::kStatusError, self);
2331 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002332 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002333 }
2334 CHECK(klass->IsLoaded());
2335 // Link the class (if necessary)
2336 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002337 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002338 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002339
2340 mirror::Class* new_class = nullptr;
2341 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002342 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002343 if (!klass->IsErroneous()) {
2344 klass->SetStatus(mirror::Class::kStatusError, self);
2345 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002346 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002347 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002348 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002349 CHECK(new_class != nullptr) << descriptor;
2350 CHECK(new_class->IsResolved()) << descriptor;
2351
2352 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002353
2354 /*
2355 * We send CLASS_PREPARE events to the debugger from here. The
2356 * definition of "preparation" is creating the static fields for a
2357 * class and initializing them to the standard default values, but not
2358 * executing any code (that comes later, during "initialization").
2359 *
2360 * We did the static preparation in LinkClass.
2361 *
2362 * The class has been prepared and resolved but possibly not yet verified
2363 * at this point.
2364 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002365 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002366
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002367 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002368}
2369
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002370uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2371 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002372 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002373 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002374 size_t num_8 = 0;
2375 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002376 size_t num_32 = 0;
2377 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002378 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002379 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2380 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002381 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002382 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002383 switch (c) {
2384 case 'L':
2385 case '[':
2386 num_ref++;
2387 break;
2388 case 'J':
2389 case 'D':
2390 num_64++;
2391 break;
2392 case 'I':
2393 case 'F':
2394 num_32++;
2395 break;
2396 case 'S':
2397 case 'C':
2398 num_16++;
2399 break;
2400 case 'B':
2401 case 'Z':
2402 num_8++;
2403 break;
2404 default:
2405 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002406 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002407 }
2408 }
2409 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002410 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002411}
2412
Ian Rogers97b52f82014-08-14 11:34:07 -07002413OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2414 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002415 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002416 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2417 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002418 *found = false;
2419 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002420 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002421 *found = true;
2422 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002423}
2424
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002425static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2426 uint32_t method_idx) {
2427 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002428 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002429 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002430 ClassDataItemIterator it(dex_file, class_data);
2431 // Skip fields
2432 while (it.HasNextStaticField()) {
2433 it.Next();
2434 }
2435 while (it.HasNextInstanceField()) {
2436 it.Next();
2437 }
2438 // Process methods
2439 size_t class_def_method_index = 0;
2440 while (it.HasNextDirectMethod()) {
2441 if (it.GetMemberIndex() == method_idx) {
2442 return class_def_method_index;
2443 }
2444 class_def_method_index++;
2445 it.Next();
2446 }
2447 while (it.HasNextVirtualMethod()) {
2448 if (it.GetMemberIndex() == method_idx) {
2449 return class_def_method_index;
2450 }
2451 class_def_method_index++;
2452 it.Next();
2453 }
2454 DCHECK(!it.HasNext());
2455 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002456 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002457}
2458
Ian Rogers97b52f82014-08-14 11:34:07 -07002459const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002460 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002461 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002462 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002463 size_t oat_method_index;
2464 if (method->IsStatic() || method->IsDirect()) {
2465 // Simple case where the oat method index was stashed at load time.
2466 oat_method_index = method->GetMethodIndex();
2467 } else {
2468 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2469 // by search for its position in the declared virtual methods.
2470 oat_method_index = declaring_class->NumDirectMethods();
2471 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002472 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002473 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002474 // Check method index instead of identity in case of duplicate method definitions.
2475 if (method->GetDexMethodIndex() ==
2476 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002477 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002478 break;
2479 }
Ian Rogersf320b632012-03-13 18:47:47 -07002480 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002481 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002482 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2483 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002484 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002485 DCHECK_EQ(oat_method_index,
2486 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002487 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002488 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002489 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2490 declaring_class->GetDexClassDefIndex(),
2491 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002492 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002493 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002494 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002495 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002496}
2497
2498// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002499const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002500 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002501 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002502 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002503 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002504 bool found;
2505 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002506 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002507 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002508 result = oat_method.GetQuickCode();
2509 }
2510
Ian Rogersef7d42f2014-01-06 12:55:46 -08002511 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002512 if (method->IsNative()) {
2513 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002514 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002515 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002516 // No code? Do we expect portable code?
2517 result = GetQuickToPortableBridge();
2518 } else {
2519 // No code? You must mean to go into the interpreter.
2520 result = GetQuickToInterpreterBridge();
2521 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002522 }
2523 return result;
TDYa12785321912012-04-01 15:24:56 -07002524}
2525
Ian Rogersef7d42f2014-01-06 12:55:46 -08002526const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2527 bool* have_portable_code) {
2528 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2529 *have_portable_code = false;
2530 if (method->IsProxyMethod()) {
2531 return GetPortableProxyInvokeHandler();
2532 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002533 bool found;
2534 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002535 const void* result = nullptr;
2536 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002537 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002538 result = oat_method.GetPortableCode();
2539 quick_code = oat_method.GetQuickCode();
2540 }
2541
Ian Rogersef7d42f2014-01-06 12:55:46 -08002542 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002543 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002544 // No code? You must mean to go into the interpreter.
2545 result = GetPortableToInterpreterBridge();
2546 } else {
2547 // No code? But there's quick code, so use a bridge.
2548 result = GetPortableToQuickBridge();
2549 }
2550 } else {
2551 *have_portable_code = true;
2552 }
2553 return result;
2554}
2555
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002556const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2557 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2558 return nullptr;
2559 }
2560 bool found;
2561 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2562 return found ? oat_method.GetQuickCode() : nullptr;
2563}
2564
2565const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2566 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2567 return nullptr;
2568 }
2569 bool found;
2570 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2571 return found ? oat_method.GetPortableCode() : nullptr;
2572}
2573
Ian Rogersef7d42f2014-01-06 12:55:46 -08002574const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2575 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002576 bool found;
2577 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2578 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002579 return nullptr;
2580 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002581 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002582 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002583}
2584
2585const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2586 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002587 bool found;
2588 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2589 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002590 return nullptr;
2591 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002592 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002593 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002594}
2595
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002596// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002597static bool NeedsInterpreter(
2598 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2599 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002600 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002601 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002602 // May return true for native code, in the case of generic JNI
2603 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002604 return true;
2605 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002606#ifdef ART_SEA_IR_MODE
2607 ScopedObjectAccess soa(Thread::Current());
2608 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2609 LOG(INFO) << "Found " << PrettyMethod(method);
2610 return false;
2611 }
2612#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002613 // If interpreter mode is enabled, every method (except native and proxy) must
2614 // be run with interpreter.
2615 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2616 !method->IsNative() && !method->IsProxyMethod();
2617}
2618
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002619void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002620 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002621 if (klass->NumDirectMethods() == 0) {
2622 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002623 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002624 Runtime* runtime = Runtime::Current();
2625 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002626 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2627 return; // OAT file unavailable.
2628 }
Ian Rogers19846512012-02-24 11:42:47 -08002629 }
Alex Light64ad14d2014-08-19 14:23:13 -07002630
Mathieu Chartierf8322842014-05-16 10:59:25 -07002631 const DexFile& dex_file = klass->GetDexFile();
2632 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002633 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002634 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002635 // There should always be class data if there were direct methods.
2636 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002637 ClassDataItemIterator it(dex_file, class_data);
2638 // Skip fields
2639 while (it.HasNextStaticField()) {
2640 it.Next();
2641 }
2642 while (it.HasNextInstanceField()) {
2643 it.Next();
2644 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002645 bool has_oat_class;
2646 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2647 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002648 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002649 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002650 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002651 if (!method->IsStatic()) {
2652 // Only update static methods.
2653 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002654 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002655 const void* portable_code = nullptr;
2656 const void* quick_code = nullptr;
2657 if (has_oat_class) {
2658 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2659 portable_code = oat_method.GetPortableCode();
2660 quick_code = oat_method.GetQuickCode();
2661 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002662 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2663 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002664 if (enter_interpreter) {
2665 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002666 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002667 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002668 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002669 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002670 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002671 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002672 quick_code = GetQuickToInterpreterBridge();
2673 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002674 } else {
2675 if (portable_code == nullptr) {
2676 portable_code = GetPortableToQuickBridge();
2677 } else {
2678 have_portable_code = true;
2679 }
2680 if (quick_code == nullptr) {
2681 quick_code = GetQuickToPortableBridge();
2682 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002683 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002684 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2685 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002686 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002687 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002688}
2689
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002690void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002691 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002692 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002693 Runtime* runtime = Runtime::Current();
2694 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002695 // The following code only applies to a non-compiler runtime.
2696 return;
2697 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002698 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002699 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2700 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002701 if (oat_class != nullptr) {
2702 // Every kind of method should at least get an invoke stub from the oat_method.
2703 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002704 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002705 oat_method.LinkMethod(method.Get());
2706 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002707
Jeff Hao16743632013-05-08 10:59:04 -07002708 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002709 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002710 method->GetEntryPointFromQuickCompiledCode(),
2711 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002712 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002713 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002714 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002715 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002716 }
2717
Brian Carlstrom92827a52011-10-10 15:50:01 -07002718 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002719 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2720 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002721 return;
2722 }
Ian Rogers19846512012-02-24 11:42:47 -08002723
Ian Rogersef7d42f2014-01-06 12:55:46 -08002724 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002725 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002726 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002727 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2728 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002729 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2730 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002731 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002732 if (!method->IsNative()) {
2733 // Set entry point from compiled code if there's no code or in interpreter only mode.
2734 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2735 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2736 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002737 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002738 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2739 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002740 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2741 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2742 have_portable_code = true;
2743 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2744 } else {
2745 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2746 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002747 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002748
Ian Rogers62d6c772013-02-27 08:32:07 -08002749 if (method->IsNative()) {
2750 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002751 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002752
2753 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002754 // We have a native method here without code. Then it should have either the generic JNI
2755 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2756 // TODO: this doesn't handle all the cases where trampolines may be installed.
2757 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2758 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002759 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002760 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002761
Ian Rogers62d6c772013-02-27 08:32:07 -08002762 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002763 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002764 method->GetEntryPointFromQuickCompiledCode(),
2765 method->GetEntryPointFromPortableCompiledCode(),
2766 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002767}
2768
Fred Shih37f05ef2014-07-16 18:38:08 -07002769
Fred Shih37f05ef2014-07-16 18:38:08 -07002770
Ian Rogers7b078e82014-09-10 14:44:24 -07002771void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002772 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002773 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002774 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002775 CHECK(klass.Get() != nullptr);
2776 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002777 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002778 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002779 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002780
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002781 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002782 if (kUseBakerOrBrooksReadBarrier) {
2783 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002784 }
Andreas Gampe51829322014-08-25 15:05:04 -07002785 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002786 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002787 klass->SetAccessFlags(access_flags);
2788 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002789 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002790 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002791
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002792 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002793 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002794 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002795
Ian Rogers13735952014-10-08 12:43:28 -07002796 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002797 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002798 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002799 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002800
Ian Rogers97b52f82014-08-14 11:34:07 -07002801
2802 bool has_oat_class = false;
2803 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2804 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2805 &has_oat_class);
2806 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002807 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002808 }
2809 }
2810 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002811 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002812 }
2813}
2814
Ian Rogers7b078e82014-09-10 14:44:24 -07002815void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002816 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002817 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002818 const OatFile::OatClass* oat_class) {
2819 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002820 ClassDataItemIterator it(dex_file, class_data);
2821 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002822 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002823 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002824 CHECK(self->IsExceptionPending()); // OOME.
2825 return;
2826 }
2827 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002828 }
2829 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002830 mirror::ObjectArray<mirror::ArtField>* fields =
2831 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002832 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002833 CHECK(self->IsExceptionPending()); // OOME.
2834 return;
2835 }
2836 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002837 }
2838 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002839 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002840 StackHandleScope<1> hs(self);
2841 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002842 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002843 CHECK(self->IsExceptionPending()); // OOME.
2844 return;
2845 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002846 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002847 LoadField(dex_file, it, klass, sfield);
2848 }
2849 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002850 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002851 StackHandleScope<1> hs(self);
2852 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002853 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002854 CHECK(self->IsExceptionPending()); // OOME.
2855 return;
2856 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002857 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002858 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002859 }
2860
Ian Rogers0571d352011-11-03 19:51:38 -07002861 // Load methods.
2862 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002863 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002864 mirror::ObjectArray<mirror::ArtMethod>* directs =
2865 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002866 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002867 CHECK(self->IsExceptionPending()); // OOME.
2868 return;
2869 }
2870 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002871 }
Ian Rogers0571d352011-11-03 19:51:38 -07002872 if (it.NumVirtualMethods() != 0) {
2873 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002874 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2875 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002876 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002877 CHECK(self->IsExceptionPending()); // OOME.
2878 return;
2879 }
2880 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002881 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002882 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002883 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2884 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002885 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002886 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002887 StackHandleScope<1> hs(self);
2888 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002889 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002890 CHECK(self->IsExceptionPending()); // OOME.
2891 return;
2892 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002893 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002894 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002895 uint32_t it_method_index = it.GetMemberIndex();
2896 if (last_dex_method_index == it_method_index) {
2897 // duplicate case
2898 method->SetMethodIndex(last_class_def_method_index);
2899 } else {
2900 method->SetMethodIndex(class_def_method_index);
2901 last_dex_method_index = it_method_index;
2902 last_class_def_method_index = class_def_method_index;
2903 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002904 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002905 }
2906 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002907 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002908 StackHandleScope<1> hs(self);
2909 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002910 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002911 CHECK(self->IsExceptionPending()); // OOME.
2912 return;
2913 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002914 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002915 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002916 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002917 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002918 }
2919 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002920}
2921
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002922void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002923 Handle<mirror::Class> klass,
2924 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002925 uint32_t field_idx = it.GetMemberIndex();
2926 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002927 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002928 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002929}
2930
Brian Carlstromea46f952013-07-30 01:26:50 -07002931mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002932 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002933 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002934 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002935 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002936 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002937
Brian Carlstromea46f952013-07-30 01:26:50 -07002938 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002939 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002940 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002941 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002942 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002943 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002944
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002945 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002946 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002947 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002948 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002949
Ian Rogers19846512012-02-24 11:42:47 -08002950 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002951 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002952
Andreas Gampe51829322014-08-25 15:05:04 -07002953 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002954
Ian Rogersdfb325e2013-10-30 01:00:44 -07002955 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002956 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002957 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2958 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002959 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002960 klass->SetFinalizable();
2961 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002962 std::string temp;
2963 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002964 // The Enum class declares a "final" finalize() method to prevent subclasses from
2965 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2966 // subclasses, so we exclude it here.
2967 // We also want to avoid setting the flag on Object, where we know that finalize() is
2968 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002969 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2970 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002971 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002972 }
2973 }
2974 }
2975 } else if (method_name[0] == '<') {
2976 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002977 bool is_init = (strcmp("<init>", method_name) == 0);
2978 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002979 if (UNLIKELY(!is_init && !is_clinit)) {
2980 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2981 } else {
2982 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2983 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002984 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002985 access_flags |= kAccConstructor;
2986 }
2987 }
2988 }
2989 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002990
Mathieu Chartier66f19252012-09-18 08:57:04 -07002991 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002992}
2993
Ian Rogers7b078e82014-09-10 14:44:24 -07002994void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002995 StackHandleScope<1> hs(self);
2996 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002997 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2998 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002999 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003000}
3001
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003002void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003003 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003004 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003005 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003006 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003007}
3008
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003009bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003010 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07003011 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003012 mirror::DexCache* dex_cache = GetDexCache(i);
3013 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08003014 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003015 }
3016 }
3017 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003018}
3019
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003020bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003021 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003022 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003023}
3024
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003025void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003026 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003027 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003028 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003029 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3030 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003031 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003032 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003033 if (log_new_dex_caches_roots_) {
3034 // TODO: This is not safe if we can remove dex caches.
3035 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3036 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003037}
3038
Brian Carlstromaded5f72011-10-07 17:15:04 -07003039void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003040 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003041 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003042 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003043 if (IsDexFileRegisteredLocked(dex_file)) {
3044 return;
3045 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003046 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003047 // Don't alloc while holding the lock, since allocation may need to
3048 // suspend all threads and another thread may need the dex_lock_ to
3049 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003050 StackHandleScope<1> hs(self);
3051 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003052 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3053 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003054 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003055 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003056 if (IsDexFileRegisteredLocked(dex_file)) {
3057 return;
3058 }
3059 RegisterDexFileLocked(dex_file, dex_cache);
3060 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003061}
3062
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003063void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003064 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003065 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003066 RegisterDexFileLocked(dex_file, dex_cache);
3067}
3068
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003069mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003070 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003071 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003072 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003073 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003074 if (dex_cache->GetDexFile() == &dex_file) {
3075 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003076 }
3077 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003078 // Search matching by location name.
3079 std::string location(dex_file.GetLocation());
3080 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003081 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003082 if (dex_cache->GetDexFile()->GetLocation() == location) {
3083 return dex_cache;
3084 }
3085 }
3086 // Failure, dump diagnostic and abort.
3087 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003088 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003089 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3090 }
3091 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003092 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003093}
3094
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003095void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003096 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003097 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003098 mirror::DexCache* dex_cache = GetDexCache(i);
3099 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003100 }
3101}
3102
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003103mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003104 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003105 if (UNLIKELY(klass == nullptr)) {
3106 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003107 }
3108 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003109}
3110
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003111mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3112 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003113 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003114 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003115 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003116 StackHandleScope<1> hs(self);
3117 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003118 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003119 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003120 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003121 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3122 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003123 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3124 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003125 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003126 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003127}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003128
Brian Carlstrombe977852011-07-19 14:54:54 -07003129// Create an array class (i.e. the class object for the array, not the
3130// array itself). "descriptor" looks like "[C" or "[[[[B" or
3131// "[Ljava/lang/String;".
3132//
3133// If "descriptor" refers to an array of primitives, look up the
3134// primitive type's internally-generated class object.
3135//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003136// "class_loader" is the class loader of the class that's referring to
3137// us. It's used to ensure that we're looking for the element type in
3138// the right context. It does NOT become the class loader for the
3139// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003140//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003141// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003142mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003143 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003144 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003145 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003146 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003147 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3148 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003149 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003150 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003151 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003152 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3153 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003154 if (component_type.Get() == nullptr) {
3155 DCHECK(self->IsExceptionPending());
3156 return nullptr;
3157 } else {
3158 self->ClearException();
3159 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003160 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003161 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3162 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3163 return nullptr;
3164 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003165 // See if the component type is already loaded. Array classes are
3166 // always associated with the class loader of their underlying
3167 // element type -- an array of Strings goes with the loader for
3168 // java/lang/String -- so we need to look for it there. (The
3169 // caller should have checked for the existence of the class
3170 // before calling here, but they did so with *their* class loader,
3171 // not the component type's loader.)
3172 //
3173 // If we find it, the caller adds "loader" to the class' initiating
3174 // loader list, which should prevent us from going through this again.
3175 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003176 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003177 // are the same, because our caller (FindClass) just did the
3178 // lookup. (Even if we get this wrong we still have correct behavior,
3179 // because we effectively do this lookup again when we add the new
3180 // class to the hash table --- necessary because of possible races with
3181 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003182 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003183 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003184 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003185 return new_class;
3186 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003187 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003188
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003189 // Fill out the fields in the Class.
3190 //
3191 // It is possible to execute some methods against arrays, because
3192 // all arrays are subclasses of java_lang_Object_, so we need to set
3193 // up a vtable. We can just point at the one in java_lang_Object_.
3194 //
3195 // Array classes are simple enough that we don't need to do a full
3196 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003197 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003198 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003199 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003200 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003201 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003202 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003203 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003204 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003205 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003206 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003207 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003208 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003209 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003210 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003211 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003212 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003213 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003214 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003215 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003216 }
3217 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003218 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003219 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003220 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003221 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003222 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003223 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003224 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003225 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003226 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003227 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003228 new_class->SetSuperClass(java_lang_Object);
3229 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003230 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003231 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003232 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003233 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003234 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3235 Runtime::Current()->GetImtUnimplementedMethod());
3236 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003237 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003238 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003239 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003240 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003241
3242
3243 // All arrays have java/lang/Cloneable and java/io/Serializable as
3244 // interfaces. We need to set that up here, so that stuff like
3245 // "instanceof" works right.
3246 //
3247 // Note: The GC could run during the call to FindSystemClass,
3248 // so we need to make sure the class object is GC-valid while we're in
3249 // there. Do this by clearing the interface list so the GC will just
3250 // think that the entries are null.
3251
3252
3253 // Use the single, global copies of "interfaces" and "iftable"
3254 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003255 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003256 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003257 CHECK(array_iftable != nullptr);
3258 new_class->SetIfTable(array_iftable);
3259 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003260
Elliott Hughes00626c22013-06-14 15:04:14 -07003261 // Inherit access flags from the component type.
3262 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3263 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3264 access_flags &= kAccJavaFlagsMask;
3265 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003266 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003267 access_flags |= kAccAbstract | kAccFinal;
3268 access_flags &= ~kAccInterface;
3269
3270 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003271
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003272 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003273 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003274 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003275 }
3276 // Another thread must have loaded the class after we
3277 // started but before we finished. Abandon what we've
3278 // done.
3279 //
3280 // (Yes, this happens.)
3281
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003282 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003283}
3284
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003285mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003286 switch (type) {
3287 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003288 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003289 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003290 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003291 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003292 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003293 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003294 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003295 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003296 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003297 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003298 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003299 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003300 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003301 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003302 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003303 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003304 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003305 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003306 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003307 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003308 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003309 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003310 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003311}
3312
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003313mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3314 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003315 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003316 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003317 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003318 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003319 source += " from ";
3320 source += dex_cache->GetLocation()->ToModifiedUtf8();
3321 }
3322 LOG(INFO) << "Loaded class " << descriptor << source;
3323 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003324 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003325 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003326 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003327 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003328 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003329 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003330 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003331 // Check a class loaded with the system class loader matches one in the image if the class
3332 // is in the image.
3333 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003334 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003335 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003336 }
3337 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003338 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003339 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003340 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003341 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003342 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003343 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003344}
3345
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003346mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3347 size_t hash) {
3348 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003349 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3350 hash);
3351 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003352 CHECK(klass->IsProxyClass());
3353 return nullptr;
3354 }
3355
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003356 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003357 CHECK_NE(existing, klass) << descriptor;
3358 CHECK(!existing->IsResolved()) << descriptor;
3359 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3360
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003361 CHECK(!klass->IsTemp()) << descriptor;
3362 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3363 dex_cache_image_class_lookup_required_) {
3364 // Check a class loaded with the system class loader matches one in the image if the class
3365 // is in the image.
3366 existing = LookupClassFromImage(descriptor);
3367 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003368 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003369 }
3370 }
3371 VerifyObject(klass);
3372
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003373 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003374 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003375 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003376 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003377 }
3378
3379 return existing;
3380}
3381
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003382bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003383 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003384 auto pair = std::make_pair(descriptor, class_loader);
3385 auto it = class_table_.Find(pair);
3386 if (it != class_table_.end()) {
3387 class_table_.Erase(it);
3388 return true;
3389 }
3390 it = pre_zygote_class_table_.Find(pair);
3391 if (it != pre_zygote_class_table_.end()) {
3392 pre_zygote_class_table_.Erase(it);
3393 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003394 }
3395 return false;
3396}
3397
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003398mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003399 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003400 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003401 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003402 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003403 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003404 return result;
3405 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003406 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003407 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3408 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003409 } else {
3410 // Lookup failed but need to search dex_caches_.
3411 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003412 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003413 InsertClass(descriptor, result, hash);
3414 } else {
3415 // Searching the image dex files/caches failed, we don't want to get into this situation
3416 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3417 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003418 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003419 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3420 MoveImageClassesToClassTable();
3421 }
3422 }
3423 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003424 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003425}
3426
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003427mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003428 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003429 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003430 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3431 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3432 if (it == pre_zygote_class_table_.end()) {
3433 it = class_table_.FindWithHash(descriptor_pair, hash);
3434 if (it == class_table_.end()) {
3435 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003436 }
3437 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003438 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003439}
3440
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003441static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3442 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3443 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003444 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003445 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3446 return root->AsObjectArray<mirror::DexCache>();
3447}
3448
3449void ClassLinker::MoveImageClassesToClassTable() {
3450 Thread* self = Thread::Current();
3451 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3452 if (!dex_cache_image_class_lookup_required_) {
3453 return; // All dex cache classes are already in the class table.
3454 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003455 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003456 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003457 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003458 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3459 mirror::DexCache* dex_cache = dex_caches->Get(i);
3460 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3461 for (int32_t j = 0; j < types->GetLength(); j++) {
3462 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003463 if (klass != nullptr) {
3464 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003465 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003466 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003467 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3468 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003469 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003470 << PrettyClassAndClassLoader(klass);
3471 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003472 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003473 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003474 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003475 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003476 }
3477 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003478 }
3479 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003480 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003481}
3482
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003483void ClassLinker::MoveClassTableToPreZygote() {
3484 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3485 DCHECK(pre_zygote_class_table_.Empty());
3486 pre_zygote_class_table_ = std::move(class_table_);
3487 class_table_.Clear();
3488}
3489
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003490mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003491 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003492 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3493 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3494 mirror::DexCache* dex_cache = dex_caches->Get(i);
3495 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003496 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003497 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003498 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003499 const DexFile::TypeId* type_id =
3500 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003501 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003502 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3503 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003504 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003505 return klass;
3506 }
3507 }
3508 }
3509 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003510 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003511}
3512
3513void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3514 result.clear();
3515 if (dex_cache_image_class_lookup_required_) {
3516 MoveImageClassesToClassTable();
3517 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003518 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3519 while (true) {
3520 auto it = class_table_.Find(descriptor);
3521 if (it == class_table_.end()) {
3522 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003523 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003524 result.push_back(it->Read());
3525 class_table_.Erase(it);
3526 }
3527 for (mirror::Class* k : result) {
3528 class_table_.Insert(GcRoot<mirror::Class>(k));
3529 }
3530 size_t pre_zygote_start = result.size();
3531 // Now handle the pre zygote table.
3532 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3533 // called from the debugger.
3534 while (true) {
3535 auto it = pre_zygote_class_table_.Find(descriptor);
3536 if (it == pre_zygote_class_table_.end()) {
3537 break;
3538 }
3539 result.push_back(it->Read());
3540 pre_zygote_class_table_.Erase(it);
3541 }
3542 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3543 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003544 }
3545}
3546
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003547void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003548 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003549 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003550
Ian Rogers9ffb0392012-09-10 11:56:50 -07003551 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003552 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003553 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003554 return;
3555 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003556 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3557 return;
3558 }
jeffhao98eacac2011-09-14 16:11:53 -07003559
Ian Rogers9ffb0392012-09-10 11:56:50 -07003560 // The class might already be erroneous, for example at compile time if we attempted to verify
3561 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003562 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003563 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003564 return;
3565 }
3566
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003567 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003568 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003569 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003570 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003571 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003572 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003573 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003574 }
jeffhao98eacac2011-09-14 16:11:53 -07003575
Jeff Hao4a200f52014-04-01 14:58:49 -07003576 // Skip verification if disabled.
3577 if (!Runtime::Current()->IsVerificationEnabled()) {
3578 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003579 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003580 return;
3581 }
3582
Ian Rogers9ffb0392012-09-10 11:56:50 -07003583 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003584 StackHandleScope<2> hs(self);
3585 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003586 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003587 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003588 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003589
3590 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003591 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003592 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003593 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003594 std::string error_msg(
3595 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3596 PrettyDescriptor(klass.Get()).c_str(),
3597 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003598 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003599 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3600 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003601 self->ClearException();
3602 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003603 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3604 if (cause.Get() != nullptr) {
3605 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003606 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003607 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003608 if (Runtime::Current()->IsCompiler()) {
3609 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3610 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003611 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003612 return;
3613 }
3614 }
3615
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003616 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003617 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003618 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003619 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003620 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003621 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003622 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003623 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003624 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3625 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003626 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003627 return;
3628 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003629 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003630 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003631 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003632 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003633 Runtime::Current()->IsCompiler(),
3634 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003635 }
3636 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003637 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003638 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003639 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3640 << " because: " << error_msg;
3641 }
Ian Rogers1f539342012-10-03 21:09:42 -07003642 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003643 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003644 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003645 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003646 // Even though there were no verifier failures we need to respect whether the super-class
3647 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003648 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003649 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003650 } else {
3651 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003652 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003653 // Pretend a soft failure occured so that we don't consider the class verified below.
3654 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003655 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003656 } else {
3657 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3658 // Soft failures at compile time should be retried at runtime. Soft
3659 // failures at runtime will be handled by slow paths in the generated
3660 // code. Set status accordingly.
3661 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003662 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003663 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003664 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003665 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3666 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003667 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003668 }
3669 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003670 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003671 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003672 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3673 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003674 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003675 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003676 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003677 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003678 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003679 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003680 // Let the interpreter know it by setting the kAccPreverified flag onto each
3681 // method.
3682 // Note: we're going here during compilation and at runtime. When we set the
3683 // kAccPreverified flag when compiling image classes, the flag is recorded
3684 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003685 EnsurePreverifiedMethods(klass);
3686 }
3687}
3688
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003689void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003690 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003691 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003692 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003693 }
jeffhao98eacac2011-09-14 16:11:53 -07003694}
3695
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003696bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3697 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003698 // If we're compiling, we can only verify the class using the oat file if
3699 // we are not compiling the image or if the class we're verifying is not part of
3700 // the app. In other words, we will only check for preverification of bootclasspath
3701 // classes.
3702 if (Runtime::Current()->IsCompiler()) {
3703 // Are we compiling the bootclasspath?
3704 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3705 return false;
3706 }
3707 // We are compiling an app (not the image).
3708
3709 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003710 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003711 return false;
3712 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003713 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003714
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003715 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003716 // In case we run without an image there won't be a backing oat file.
3717 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003718 return false;
3719 }
3720
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003721 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003722 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003723 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3724 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003725 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003726 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003727 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003728 // Compile time verification failed with a soft error. Compile time verification can fail
3729 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003730 // class ... {
3731 // Foo x;
3732 // .... () {
3733 // if (...) {
3734 // v1 gets assigned a type of resolved class Foo
3735 // } else {
3736 // v1 gets assigned a type of unresolved class Bar
3737 // }
3738 // iput x = v1
3739 // } }
3740 // when we merge v1 following the if-the-else it results in Conflict
3741 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3742 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3743 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3744 // at compile time).
3745 return false;
3746 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003747 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003748 // Compile time verification failed with a hard error. This is caused by invalid instructions
3749 // in the class. These errors are unrecoverable.
3750 return false;
3751 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003752 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003753 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3754 // not loading the class.
3755 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3756 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003757 return false;
3758 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003759 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003760 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003761 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003762 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003763 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003764}
3765
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003766void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003767 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003768 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3769 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3770 }
3771 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3772 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3773 }
3774}
3775
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003776void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003777 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003778 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3779 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003780 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003781 return; // native or abstract method
3782 }
3783 if (code_item->tries_size_ == 0) {
3784 return; // nothing to process
3785 }
Ian Rogers13735952014-10-08 12:43:28 -07003786 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003787 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3788 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3789 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3790 CatchHandlerIterator iterator(handlers_ptr);
3791 for (; iterator.HasNext(); iterator.Next()) {
3792 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3793 // unresolved exception types will be ignored by exception delivery
3794 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003795 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003796 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003797 DCHECK(Thread::Current()->IsExceptionPending());
3798 Thread::Current()->ClearException();
3799 }
3800 }
3801 }
3802 handlers_ptr = iterator.EndDataPointer();
3803 }
3804}
3805
Brian Carlstromea46f952013-07-30 01:26:50 -07003806static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003807static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3808 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003809
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003810mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003811 jobjectArray interfaces, jobject loader,
3812 jobjectArray methods, jobjectArray throws) {
3813 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003814 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003815 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003816 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003817 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003818 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003819 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003820 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003821 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003822 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003823 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3824 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003825 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003826 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003827 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003828 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003829 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003830 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003831
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003832 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003833 {
3834 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003835 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003836 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003837 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003838 }
3839 klass->SetSFields(sfields);
3840 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003841 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3842 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003843 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3844 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003845 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003846 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003847 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003848 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003849 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003850 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003851 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3852 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003853 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3854 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003855 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003856 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003857 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003858 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003859 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003860 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003861 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003862
Ian Rogers466bb252011-10-14 03:29:56 -07003863 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003864 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003865 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003866 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003867 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003868 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003869 }
3870 klass->SetDirectMethods(directs);
3871 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003872 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003873 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003874 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003875 }
3876 klass->SetDirectMethod(0, constructor);
3877 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003878
Mathieu Chartier590fee92013-09-13 13:46:47 -07003879 // Create virtual method using specified prototypes.
3880 size_t num_virtual_methods =
3881 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003882 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003883 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3884 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003885 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003886 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003887 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003888 }
3889 klass->SetVirtualMethods(virtuals);
3890 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003891 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003892 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003893 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3894 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003895 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003896 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003897 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003898 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003899 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003900 }
3901 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003902 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003903
3904 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003905 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003906 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003907
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003908 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3909 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003910 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003911 // Must hold lock on object when resolved.
3912 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003913 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003914 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003915 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003916 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003917 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003918 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003919 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003920 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003921
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003922 CHECK(klass->IsRetired());
3923 CHECK_NE(klass.Get(), new_class);
3924 klass.Assign(new_class);
3925
3926 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003927 interfaces_sfield->SetObject<false>(klass.Get(),
3928 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003929 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003930 throws_sfield->SetObject<false>(klass.Get(),
3931 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003932
3933 {
3934 // Lock on klass is released. Lock new class object.
3935 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003936 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003937 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003938
3939 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003940 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003941 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003942 CheckProxyConstructor(klass->GetDirectMethod(0));
3943 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003944 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003945 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3946 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003947 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3948 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003949 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003950 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003951
Mathieu Chartier590fee92013-09-13 13:46:47 -07003952 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003953 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003954 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003955 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3956
3957 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003958 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003959 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003960
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003961 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003962 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003963 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003964 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003965 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003966 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3967 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003968 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003969 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003970}
3971
Ian Rogersef7d42f2014-01-06 12:55:46 -08003972std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003973 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003974 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003975 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003976 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3977}
3978
Ian Rogersef7d42f2014-01-06 12:55:46 -08003979mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3980 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003981 DCHECK(proxy_class->IsProxyClass());
3982 DCHECK(proxy_method->IsProxyMethod());
3983 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003984 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003985 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003986 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003987 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003988 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003989 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003990 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003991 break;
3992 }
3993 }
3994 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003995 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003996 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003997 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003998 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003999 return resolved_method;
4000}
4001
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004002
Brian Carlstromea46f952013-07-30 01:26:50 -07004003mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004004 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07004005 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07004006 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07004007 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004008 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07004009 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
4010 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02004011 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4012 // constructor method.
4013 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
4014 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07004015 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4016 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07004017 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
4018 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004019 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07004020 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004021 }
Ian Rogers466bb252011-10-14 03:29:56 -07004022 // Make this constructor public and fix the class to be our Proxy version
4023 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004024 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004025 return constructor;
4026}
4027
Brian Carlstromea46f952013-07-30 01:26:50 -07004028static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004029 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004030 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004031 CHECK_STREQ(constructor->GetName(), "<init>");
4032 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4033 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004034 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004035}
4036
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004037mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004038 Handle<mirror::Class> klass,
4039 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004040 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4041 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004042 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004043 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004044 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004045 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004046 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004047 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004048 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004049 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004050 }
Ian Rogers466bb252011-10-14 03:29:56 -07004051
4052 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4053 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004054 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004055 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004056
Ian Rogers466bb252011-10-14 03:29:56 -07004057 // At runtime the method looks like a reference and argument saving method, clone the code
4058 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004059 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4060 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004061 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004062
Ian Rogersc2b44472011-12-14 21:17:17 -08004063 return method;
4064}
Jesse Wilson95caa792011-10-12 18:14:17 -04004065
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004066static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4067 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004068 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004069 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004070 CHECK(!prototype->IsFinal());
4071 CHECK(method->IsFinal());
4072 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004073
4074 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4075 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07004076 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4077 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004078 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4079
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004080 CHECK_STREQ(method->GetName(), prototype->GetName());
4081 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004082 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004083 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004084}
4085
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004086static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4087 bool can_init_parents)
4088 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004089 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004090 return true;
4091 }
4092 if (!can_init_statics) {
4093 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004094 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004095 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004096 return false;
4097 }
4098 // Check if there are encoded static values needing initialization.
4099 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004100 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004101 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004102 if (dex_class_def->static_values_off_ != 0) {
4103 return false;
4104 }
4105 }
4106 }
4107 if (!klass->IsInterface() && klass->HasSuperClass()) {
4108 mirror::Class* super_class = klass->GetSuperClass();
4109 if (!can_init_parents && !super_class->IsInitialized()) {
4110 return false;
4111 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004112 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004113 return false;
4114 }
4115 }
4116 }
4117 return true;
4118}
4119
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004120bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004121 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004122 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4123
4124 // Are we already initialized and therefore done?
4125 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4126 // an initialized class will never change its state.
4127 if (klass->IsInitialized()) {
4128 return true;
4129 }
4130
4131 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004132 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004133 return false;
4134 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004135
Ian Rogers7b078e82014-09-10 14:44:24 -07004136 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004137 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004138 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004139 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004140
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004141 // Re-check under the lock in case another thread initialized ahead of us.
4142 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004143 return true;
4144 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004145
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004146 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004147 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004148 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004149 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004150 return false;
4151 }
4152
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004153 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004154
4155 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004156 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004157 if (!klass->IsVerified()) {
4158 // We failed to verify, expect either the klass to be erroneous or verification failed at
4159 // compile time.
4160 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004161 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004162 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004163 } else {
4164 CHECK(Runtime::Current()->IsCompiler());
4165 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004166 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004167 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004168 } else {
4169 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004170 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004171 }
4172
Brian Carlstromd1422f82011-09-28 11:37:09 -07004173 // If the class is kStatusInitializing, either this thread is
4174 // initializing higher up the stack or another thread has beat us
4175 // to initializing and we need to wait. Either way, this
4176 // invocation of InitializeClass will not be responsible for
4177 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004178 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004179 // Could have got an exception during verification.
4180 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004181 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004182 return false;
4183 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004184 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004185 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004186 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004187 return true;
4188 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004189 // No. That's fine. Wait for another thread to finish initializing.
4190 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004191 }
4192
4193 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004194 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004195 return false;
4196 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004197 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004198
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004199 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004200
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004201 // From here out other threads may observe that we're initializing and so changes of state
4202 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004203 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004204 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004205
4206 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004207 }
4208
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004209 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004210 if (!klass->IsInterface() && klass->HasSuperClass()) {
4211 mirror::Class* super_class = klass->GetSuperClass();
4212 if (!super_class->IsInitialized()) {
4213 CHECK(!super_class->IsInterface());
4214 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004215 StackHandleScope<1> hs(self);
4216 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004217 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004218 if (!super_initialized) {
4219 // The super class was verified ahead of entering initializing, we should only be here if
4220 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004221 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004222 << "Super class initialization failed for "
4223 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004224 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004225 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004226 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004227 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004228 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004229 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004230 return false;
4231 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004232 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004233 }
4234
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004235 const size_t num_static_fields = klass->NumStaticFields();
4236 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004237 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004238 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004239 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004240 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004241 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004242 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004243
4244 // Eagerly fill in static fields so that the we don't have to do as many expensive
4245 // Class::FindStaticField in ResolveField.
4246 for (size_t i = 0; i < num_static_fields; ++i) {
4247 mirror::ArtField* field = klass->GetStaticField(i);
4248 const uint32_t field_idx = field->GetDexFieldIndex();
4249 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4250 if (resolved_field == nullptr) {
4251 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004252 } else {
4253 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004254 }
4255 }
4256
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004257 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4258 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004259 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004260 ClassDataItemIterator field_it(dex_file, class_data);
4261 if (value_it.HasNext()) {
4262 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004263 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004264 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004265 StackHandleScope<1> hs2(self);
4266 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004267 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004268 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004269 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004270 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004271 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004272 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004273 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004274 }
4275 }
4276 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004277
Ian Rogersd91d6d62013-09-25 20:26:14 -07004278 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004279 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004280 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004281 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004282 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004283 }
4284
Ian Rogers7b078e82014-09-10 14:44:24 -07004285 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004286 uint64_t t1 = NanoTime();
4287
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004288 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004289 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004290 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004291
4292 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004293 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004294 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004295 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004296 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004297 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4298 RuntimeStats* thread_stats = self->GetStats();
4299 ++global_stats->class_init_count;
4300 ++thread_stats->class_init_count;
4301 global_stats->class_init_time_ns += (t1 - t0);
4302 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004303 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004304 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004305 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004306 std::string temp;
4307 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004308 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004309 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004310 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004311 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004312 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004313 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004314 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004315}
4316
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004317bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004318 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004319 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004320 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004321 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004322 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004323 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004324
4325 // When we wake up, repeat the test for init-in-progress. If
4326 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004327 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004328 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004329 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004330 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004331 return false;
4332 }
4333 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004334 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004335 continue;
4336 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004337 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004338 // Compile time initialization failed.
4339 return false;
4340 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004341 if (klass->IsErroneous()) {
4342 // The caller wants an exception, but it was thrown in a
4343 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004344 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004345 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004346 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004347 return false;
4348 }
4349 if (klass->IsInitialized()) {
4350 return true;
4351 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004352 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004353 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004354 }
Ian Rogers07140832014-09-30 15:43:59 -07004355 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004356}
4357
Ian Rogersb5fb2072014-12-02 17:22:02 -08004358static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4359 Handle<mirror::ArtMethod> method1,
4360 Handle<mirror::ArtMethod> method2)
4361 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4362 {
4363 StackHandleScope<1> hs(self);
4364 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
4365 if (UNLIKELY(method2->GetReturnType() != return_type.Get())) {
4366 return false;
4367 }
4368 }
4369 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4370 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4371 if (types1 == nullptr) {
4372 return (types2 == nullptr) || (types2->Size() == 0);
4373 } else if (UNLIKELY(types2 == nullptr)) {
4374 return types1->Size() == 0;
4375 }
4376 uint32_t num_types = types1->Size();
4377 if (UNLIKELY(num_types != types2->Size())) {
4378 return false;
4379 }
4380 for (uint32_t i = 0; i < num_types; ++i) {
4381 mirror::Class* param_type =
4382 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true);
4383 mirror::Class* other_param_type =
4384 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
4385 if (UNLIKELY(param_type != other_param_type)) {
4386 return false;
4387 }
4388 }
4389 return true;
4390}
4391
4392
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004393bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004394 if (klass->IsInterface()) {
4395 return true;
4396 }
Ian Rogers151f2212014-05-06 11:27:27 -07004397 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004398 Thread* self = Thread::Current();
4399 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004400 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
4401 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004402 if (klass->HasSuperClass() &&
4403 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004404 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004405 h_m.Assign(klass->GetVTableEntry(i));
4406 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
4407 if (h_m.Get() != super_h_m.Get() &&
4408 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004409 ThrowLinkageError(klass.Get(),
4410 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004411 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004412 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004413 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004414 return false;
4415 }
4416 }
4417 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004418 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004419 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4420 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4421 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004422 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4423 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
4424 if (h_m.Get() != super_h_m.Get() &&
4425 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004426 ThrowLinkageError(klass.Get(),
4427 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004428 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004429 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004430 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004431 return false;
4432 }
4433 }
4434 }
4435 }
4436 return true;
4437}
4438
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004439bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4440 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004441 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004442 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004443 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004444 return true;
4445 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004446 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004447 if (!success) {
4448 if (can_init_fields && can_init_parents) {
4449 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4450 }
4451 } else {
4452 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004453 }
4454 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004455}
4456
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004457void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4458 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4459 if (fields != nullptr) {
4460 for (int index = 0; index < fields->GetLength(); index ++) {
4461 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4462 fields->Get(index)->SetDeclaringClass(new_class);
4463 }
4464 }
4465 }
4466
4467 fields = new_class->GetSFields();
4468 if (fields != nullptr) {
4469 for (int index = 0; index < fields->GetLength(); index ++) {
4470 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4471 fields->Get(index)->SetDeclaringClass(new_class);
4472 }
4473 }
4474 }
4475
4476 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4477 if (methods != nullptr) {
4478 for (int index = 0; index < methods->GetLength(); index ++) {
4479 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4480 methods->Get(index)->SetDeclaringClass(new_class);
4481 }
4482 }
4483 }
4484
4485 methods = new_class->GetVirtualMethods();
4486 if (methods != nullptr) {
4487 for (int index = 0; index < methods->GetLength(); index ++) {
4488 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4489 methods->Get(index)->SetDeclaringClass(new_class);
4490 }
4491 }
4492 }
4493}
4494
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004495bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4496 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004497 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004498 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004499
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004500 if (!LinkSuperClass(klass)) {
4501 return false;
4502 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004503 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4504 self, Runtime::Current()->GetImtUnimplementedMethod());
4505 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004506 return false;
4507 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004508 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004509 return false;
4510 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004511 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004512 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004513 return false;
4514 }
4515 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004516 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004517
4518 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4519 // We don't need to retire this class as it has no embedded tables or it was created the
4520 // correct size during class linker initialization.
4521 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4522
4523 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004524 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004525 }
4526
4527 // This will notify waiters on klass that saw the not yet resolved
4528 // class in the class_table_ during EnsureResolved.
4529 klass->SetStatus(mirror::Class::kStatusResolved, self);
4530 *new_class = klass.Get();
4531 } else {
4532 CHECK(!klass->IsResolved());
4533 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004534 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004535 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004536 CHECK(self->IsExceptionPending()); // Expect an OOME.
4537 klass->SetStatus(mirror::Class::kStatusError, self);
4538 return false;
4539 }
4540
4541 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4542 StackHandleScope<1> hs(self);
4543 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4544 ObjectLock<mirror::Class> lock(self, new_class_h);
4545
4546 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4547
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004548 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4549 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004550 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004551
4552 // This will notify waiters on temp class that saw the not yet resolved class in the
4553 // class_table_ during EnsureResolved.
4554 klass->SetStatus(mirror::Class::kStatusRetired, self);
4555
4556 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4557 // This will notify waiters on new_class that saw the not yet resolved
4558 // class in the class_table_ during EnsureResolved.
4559 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004560 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004561 return true;
4562}
4563
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004564bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004565 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004566 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4567 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004568 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004569 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004570 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004571 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004572 return false;
4573 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004574 // Verify
4575 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004576 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004577 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004578 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004579 return false;
4580 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004581 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004582 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004583 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004584 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004585 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004586 for (size_t i = 0; i < interfaces->Size(); i++) {
4587 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004588 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004589 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004590 DCHECK(Thread::Current()->IsExceptionPending());
4591 return false;
4592 }
4593 // Verify
4594 if (!klass->CanAccess(interface)) {
4595 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004596 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004597 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004598 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004599 return false;
4600 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004601 }
4602 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004603 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004604 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004605 return true;
4606}
4607
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004608bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004609 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004610 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004611 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004612 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004613 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004614 return false;
4615 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004616 return true;
4617 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004618 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004619 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4620 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004621 return false;
4622 }
4623 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004624 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004625 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004626 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004627 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004628 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004629 return false;
4630 }
4631 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004632 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004633 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004634 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004635 return false;
4636 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004637
Brian Carlstromf3632832014-05-20 15:36:53 -07004638 // Inherit kAccClassIsFinalizable from the superclass in case this
4639 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004640 if (super->IsFinalizable()) {
4641 klass->SetFinalizable();
4642 }
4643
Elliott Hughes2da50362011-10-10 16:57:08 -07004644 // Inherit reference flags (if any) from the superclass.
4645 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4646 if (reference_flags != 0) {
4647 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4648 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004649 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004650 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004651 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004652 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004653 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004654 return false;
4655 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004656
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004657 if (kIsDebugBuild) {
4658 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004659 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004660 CHECK(super->IsResolved());
4661 super = super->GetSuperClass();
4662 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004663 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004664 return true;
4665}
4666
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004667// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004668bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004669 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4670 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004671 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004672 if (klass->IsInterface()) {
4673 // No vtable.
4674 size_t count = klass->NumVirtualMethods();
4675 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004676 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004677 return false;
4678 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004679 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004680 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004681 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004682 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4683 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004684 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004685 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004686}
4687
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004688// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4689// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4690// caches in the implementation below.
4691class MethodNameAndSignatureComparator FINAL : public ValueObject {
4692 public:
4693 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4694 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4695 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4696 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004697 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4698 }
4699
4700 const char* GetName() {
4701 if (name_ == nullptr) {
4702 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4703 }
4704 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004705 }
4706
4707 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4708 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4709 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4710 const DexFile* other_dex_file = other->GetDexFile();
4711 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4712 if (dex_file_ == other_dex_file) {
4713 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4714 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004715 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004716 uint32_t other_name_len;
4717 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4718 &other_name_len);
4719 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4720 return false;
4721 }
4722 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4723 }
4724
4725 private:
4726 // Dex file for the method to compare against.
4727 const DexFile* const dex_file_;
4728 // MethodId for the method to compare against.
4729 const DexFile::MethodId* const mid_;
4730 // Lazily computed name from the dex file's strings.
4731 const char* name_;
4732 // Lazily computed name length.
4733 uint32_t name_len_;
4734};
4735
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004736class LinkVirtualHashTable {
4737 public:
4738 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4739 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4740 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4741 }
4742 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4743 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4744 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004745 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004746 uint32_t index = hash % hash_size_;
4747 // Linear probe until we have an empty slot.
4748 while (hash_table_[index] != invalid_index_) {
4749 if (++index == hash_size_) {
4750 index = 0;
4751 }
4752 }
4753 hash_table_[index] = virtual_method_index;
4754 }
4755 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4756 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4757 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004758 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004759 size_t index = hash % hash_size_;
4760 while (true) {
4761 const uint32_t value = hash_table_[index];
4762 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4763 // the block and can safely assume not found.
4764 if (value == invalid_index_) {
4765 break;
4766 }
4767 if (value != removed_index_) { // This signifies not already overriden.
4768 mirror::ArtMethod* virtual_method =
4769 klass_->GetVirtualMethodDuringLinking(value);
4770 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4771 hash_table_[index] = removed_index_;
4772 return value;
4773 }
4774 }
4775 if (++index == hash_size_) {
4776 index = 0;
4777 }
4778 }
4779 return GetNotFoundIndex();
4780 }
4781 static uint32_t GetNotFoundIndex() {
4782 return invalid_index_;
4783 }
4784
4785 private:
4786 static const uint32_t invalid_index_;
4787 static const uint32_t removed_index_;
4788
4789 Handle<mirror::Class> klass_;
4790 const size_t hash_size_;
4791 uint32_t* const hash_table_;
4792};
4793
4794const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4795const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4796
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004797bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004798 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004799 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004800 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4801 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004802 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004803 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004804 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004805 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4806 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4807 if (UNLIKELY(vtable.Get() == nullptr)) {
4808 CHECK(self->IsExceptionPending()); // OOME.
4809 return false;
4810 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004811 for (size_t i = 0; i < super_vtable_length; i++) {
4812 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004813 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004814 if (num_virtual_methods == 0) {
4815 klass->SetVTable(vtable.Get());
4816 return true;
4817 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004818 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004819 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4820 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4821 if (num_virtual_methods == 0) {
4822 klass->SetVTable(super_vtable);
4823 return true;
4824 }
4825 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004826 if (UNLIKELY(vtable.Get() == nullptr)) {
4827 CHECK(self->IsExceptionPending()); // OOME.
4828 return false;
4829 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004830 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004831 // How the algorithm works:
4832 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4833 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4834 // method which has not been matched to a vtable method, and j if the virtual method at the
4835 // index overrode the super virtual method at index j.
4836 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4837 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4838 // the need for the initial vtable which we later shrink back down).
4839 // 3. Add non overridden methods to the end of the vtable.
4840 static constexpr size_t kMaxStackHash = 250;
4841 const size_t hash_table_size = num_virtual_methods * 3;
4842 uint32_t* hash_table_ptr;
4843 std::unique_ptr<uint32_t[]> hash_heap_storage;
4844 if (hash_table_size <= kMaxStackHash) {
4845 hash_table_ptr = reinterpret_cast<uint32_t*>(
4846 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4847 } else {
4848 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4849 hash_table_ptr = hash_heap_storage.get();
4850 }
4851 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4852 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004853 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004854 hash_table.Add(i);
4855 }
4856 // Loop through each super vtable method and see if they are overriden by a method we added to
4857 // the hash table.
4858 for (size_t j = 0; j < super_vtable_length; ++j) {
4859 // Search the hash table to see if we are overidden by any method.
4860 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4861 MethodNameAndSignatureComparator super_method_name_comparator(
4862 super_method->GetInterfaceMethodIfProxy());
4863 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4864 if (hash_index != hash_table.GetNotFoundIndex()) {
4865 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4866 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4867 super_method->GetAccessFlags())) {
4868 if (super_method->IsFinal()) {
4869 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4870 PrettyMethod(virtual_method).c_str(),
4871 super_method->GetDeclaringClassDescriptor());
4872 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004873 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004874 vtable->SetWithoutChecks<false>(j, virtual_method);
4875 virtual_method->SetMethodIndex(j);
4876 } else {
4877 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004878 << " would have incorrectly overridden the package-private method in "
4879 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004880 }
4881 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004882 }
4883 // Add the non overridden methods at the end.
4884 size_t actual_count = super_vtable_length;
4885 for (size_t i = 0; i < num_virtual_methods; ++i) {
4886 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4887 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4888 if (method_idx < super_vtable_length &&
4889 local_method == vtable->GetWithoutChecks(method_idx)) {
4890 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004891 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004892 vtable->SetWithoutChecks<false>(actual_count, local_method);
4893 local_method->SetMethodIndex(actual_count);
4894 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004895 }
4896 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004897 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004898 return false;
4899 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004900 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004901 CHECK_LE(actual_count, max_count);
4902 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004903 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004904 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004905 CHECK(self->IsExceptionPending()); // OOME.
4906 return false;
4907 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004908 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004909 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004910 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004911 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004912 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004913 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4914 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004915 return false;
4916 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004917 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4918 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004919 CHECK(self->IsExceptionPending()); // OOME.
4920 return false;
4921 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004922 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004923 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004924 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004925 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004926 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004927 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004928 }
4929 return true;
4930}
4931
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004932bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4933 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4934 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004935 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004936 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004937 const bool has_superclass = klass->HasSuperClass();
4938 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4939 const bool have_interfaces = interfaces.Get() != nullptr;
4940 const size_t num_interfaces =
4941 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4942 if (num_interfaces == 0) {
4943 if (super_ifcount == 0) {
4944 // Class implements no interfaces.
4945 DCHECK_EQ(klass->GetIfTableCount(), 0);
4946 DCHECK(klass->GetIfTable() == nullptr);
4947 return true;
4948 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004949 // Class implements same interfaces as parent, are any of these not marker interfaces?
4950 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004951 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004952 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004953 if (super_iftable->GetMethodArrayCount(i) > 0) {
4954 has_non_marker_interface = true;
4955 break;
4956 }
4957 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004958 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004959 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004960 klass->SetIfTable(super_iftable);
4961 return true;
4962 }
4963 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004964 size_t ifcount = super_ifcount + num_interfaces;
4965 for (size_t i = 0; i < num_interfaces; i++) {
4966 mirror::Class* interface = have_interfaces ?
4967 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4968 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004969 if (UNLIKELY(!interface->IsInterface())) {
4970 std::string temp;
4971 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4972 PrettyDescriptor(klass.Get()).c_str(),
4973 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4974 return false;
4975 }
4976 ifcount += interface->GetIfTableCount();
4977 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004978 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004979 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004980 CHECK(self->IsExceptionPending()); // OOME.
4981 return false;
4982 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004983 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004984 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004985 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004986 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004987 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004988 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004989 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004990 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004991 // Flatten the interface inheritance hierarchy.
4992 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004993 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004994 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4995 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004996 // Check if interface is already in iftable
4997 bool duplicate = false;
4998 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004999 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005000 if (existing_interface == interface) {
5001 duplicate = true;
5002 break;
5003 }
5004 }
5005 if (!duplicate) {
5006 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07005007 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005008 // Add this interface's non-duplicate super-interfaces.
5009 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005010 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005011 bool super_duplicate = false;
5012 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005013 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005014 if (existing_interface == super_interface) {
5015 super_duplicate = true;
5016 break;
5017 }
5018 }
5019 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005020 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005021 }
5022 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005023 }
5024 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005025 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08005026 // Shrink iftable in case duplicates were found
5027 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005028 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005029 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005030 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005031 CHECK(self->IsExceptionPending()); // OOME.
5032 return false;
5033 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005034 ifcount = idx;
5035 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005036 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005037 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005038 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07005039 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005040 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005041 return true;
5042 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005043 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005044 size_t max_miranda_methods = 0; // The max size of miranda_list.
5045 for (size_t i = 0; i < ifcount; ++i) {
5046 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
5047 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005048 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005049 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005050 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5051 hs.NewHandle(klass->GetVTableDuringLinking()));
5052 // Copy the IMT from the super class if possible.
5053 bool extend_super_iftable = false;
5054 if (has_superclass) {
5055 mirror::Class* super_class = klass->GetSuperClass();
5056 extend_super_iftable = true;
5057 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5058 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5059 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5060 }
5061 } else {
5062 // No imt in the super class, need to reconstruct from the iftable.
5063 mirror::IfTable* if_table = super_class->GetIfTable();
5064 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5065 const size_t length = super_class->GetIfTableCount();
5066 for (size_t i = 0; i < length; ++i) {
5067 mirror::Class* interface = iftable->GetInterface(i);
5068 const size_t num_virtuals = interface->NumVirtualMethods();
5069 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5070 DCHECK_EQ(num_virtuals, method_array_count);
5071 if (method_array_count == 0) {
5072 continue;
5073 }
5074 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5075 for (size_t j = 0; j < num_virtuals; ++j) {
5076 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5077 if (method->IsMiranda()) {
5078 continue;
5079 }
5080 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5081 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5082 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5083 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5084 out_imt->SetReference(imt_index, method);
5085 } else if (imt_ref != conflict_method) {
5086 out_imt->SetReference(imt_index, conflict_method);
5087 }
5088 }
5089 }
5090 }
5091 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005092 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005093 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005094 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005095 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005096 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005097 const bool is_super = i < super_ifcount;
5098 const bool super_interface = is_super && extend_super_iftable;
5099 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5100 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5101 if (super_interface) {
5102 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5103 DCHECK(if_table != nullptr);
5104 DCHECK(if_table->GetMethodArray(i) != nullptr);
5105 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005106 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005107 AsObjectArray<mirror::ArtMethod>());
5108 // We are overwriting a super class interface, try to only virtual methods instead of the
5109 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005110 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005111 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005112 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005113 // A new interface, we need the whole vtable incase a new interface method is implemented
5114 // in the whole superclass.
5115 input_array = vtable;
5116 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005117 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005118 CHECK(self->IsExceptionPending()); // OOME.
5119 return false;
5120 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005121 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005122 if (input_array.Get() == nullptr) {
5123 // If the added virtual methods is empty, do nothing.
5124 DCHECK(super_interface);
5125 continue;
5126 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005127 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005128 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005129 MethodNameAndSignatureComparator interface_name_comparator(
5130 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005131 int32_t k;
5132 // For each method listed in the interface's method list, find the
5133 // matching method in our class's method list. We want to favor the
5134 // subclass over the superclass, which just requires walking
5135 // back from the end of the vtable. (This only matters if the
5136 // superclass defines a private method and this class redefines
5137 // it -- otherwise it would use the same vtable slot. In .dex files
5138 // those don't end up in the virtual method table, so it shouldn't
5139 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005140 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5141 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005142 mirror::ArtMethod* vtable_method_for_name_comparison =
5143 vtable_method->GetInterfaceMethodIfProxy();
5144 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005145 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005146 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005147 ThrowIllegalAccessError(
5148 klass.Get(),
5149 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005150 PrettyMethod(vtable_method).c_str(),
5151 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005152 return false;
5153 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005154 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005155 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005156 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5157 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5158 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5159 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5160 out_imt->SetReference(imt_index, vtable_method);
5161 } else if (imt_ref != conflict_method) {
5162 // If we are not a conflict and we have the same signature and name as the imt entry,
5163 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005164 MethodNameAndSignatureComparator imt_ref_name_comparator(
5165 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005166 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005167 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005168 out_imt->SetReference(imt_index, vtable_method);
5169 } else {
5170 out_imt->SetReference(imt_index, conflict_method);
5171 }
Jeff Hao88474b42013-10-23 16:24:40 -07005172 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005173 break;
5174 }
5175 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005176 if (k < 0 && !super_interface) {
5177 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005178 for (size_t l = 0; l < miranda_list_size; ++l) {
5179 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005180 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005181 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005182 break;
5183 }
5184 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005185 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005186 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005187 miranda_method = interface_method->Clone(self)->AsArtMethod();
5188 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005189 CHECK(self->IsExceptionPending()); // OOME.
5190 return false;
5191 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005192 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005193 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005194 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005195 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005196 }
5197 }
5198 }
5199 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005200 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005201 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005202 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005203 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5204 if (old_method_count == 0) {
5205 virtuals = AllocArtMethodArray(self, new_method_count);
5206 } else {
5207 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5208 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005209 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005210 CHECK(self->IsExceptionPending()); // OOME.
5211 return false;
5212 }
5213 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005214
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005215 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005216 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005217 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005218 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005219 CHECK(self->IsExceptionPending()); // OOME.
5220 return false;
5221 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005222 for (size_t i = 0; i < miranda_list_size; ++i) {
5223 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005224 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005225 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5226 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5227 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005228 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005229 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005230 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005231 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005232 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005233
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005234 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005235 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5236 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5237 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005238 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005239 }
5240
Ian Rogers7b078e82014-09-10 14:44:24 -07005241 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005242 return true;
5243}
5244
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005245bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005246 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005247 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005248}
5249
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005250bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005251 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005252 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005253}
5254
Brian Carlstromdbc05252011-09-09 01:59:59 -07005255struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005256 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5257 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005258 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005259 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005260 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005261 // 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 -07005262 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5263 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005264 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005265 if (type1 == Primitive::kPrimNot) {
5266 // Reference always goes first.
5267 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005268 }
Vladimir Markod5777482014-11-12 17:02:02 +00005269 if (type2 == Primitive::kPrimNot) {
5270 // Reference always goes first.
5271 return false;
5272 }
5273 size_t size1 = Primitive::ComponentSize(type1);
5274 size_t size2 = Primitive::ComponentSize(type2);
5275 if (size1 != size2) {
5276 // Larger primitive types go first.
5277 return size1 > size2;
5278 }
5279 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5280 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005281 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005282 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5283 // by name and for equal names by type id index.
5284 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5285 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005286 }
5287};
5288
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005289bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005290 size_t* class_size) {
5291 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005292 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005293 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005294
Brian Carlstromea46f952013-07-30 01:26:50 -07005295 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005296 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005297
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005298 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005299 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005300 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005301 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005302 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005303 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005304 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005305 CHECK(super_class->IsResolved())
5306 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005307 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005308 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005309 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005310
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005311 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005312
Brian Carlstromdbc05252011-09-09 01:59:59 -07005313 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005314 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005315 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005316 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005317 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005318 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005319 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005320 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005321 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005322 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005323 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5324 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005325
Fred Shih381e4ca2014-08-25 17:24:27 -07005326 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005327 size_t current_field = 0;
5328 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005329 FieldGaps gaps;
5330
Brian Carlstromdbc05252011-09-09 01:59:59 -07005331 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005332 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005333 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005334 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005335 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005336 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005337 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005338 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5339 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005340 MemberOffset old_offset = field_offset;
5341 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5342 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5343 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005344 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005345 grouped_and_sorted_fields.pop_front();
5346 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005347 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005348 field_offset = MemberOffset(field_offset.Uint32Value() +
5349 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005350 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005351 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5352 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005353 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5354 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5355 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5356 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005357 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5358 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005359 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005360
Elliott Hughesadb460d2011-10-05 17:02:34 -07005361 // 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 -07005362 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005363 // We know there are no non-reference fields in the Reference classes, and we know
5364 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005365 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005366 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005367 --num_reference_fields;
5368 }
5369
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005370 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005371 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005372 if (is_static) {
5373 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005374 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005375 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005376 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005377 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005378 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
5379 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
5380 } else {
5381 std::string temp;
5382 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5383 size_t previous_size = klass->GetObjectSize();
5384 if (previous_size != 0) {
5385 // Make sure that we didn't originally have an incorrect size.
5386 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5387 }
5388 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005389 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005390 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005391 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005392
5393 if (kIsDebugBuild) {
5394 // Make sure that the fields array is ordered by name but all reference
5395 // offsets are at the beginning as far as alignment allows.
5396 MemberOffset start_ref_offset = is_static
5397 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5398 : klass->GetFirstReferenceInstanceFieldOffset();
5399 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5400 num_reference_fields *
5401 sizeof(mirror::HeapReference<mirror::Object>));
5402 MemberOffset current_ref_offset = start_ref_offset;
5403 for (size_t i = 0; i < num_fields; i++) {
5404 mirror::ArtField* field = fields->Get(i);
5405 if ((false)) { // enable to debug field layout
5406 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5407 << " class=" << PrettyClass(klass.Get())
5408 << " field=" << PrettyField(field)
5409 << " offset="
5410 << field->GetField32(mirror::ArtField::OffsetOffset());
5411 }
5412 if (i != 0) {
5413 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005414 // NOTE: The field names can be the same. This is not possible in the Java language
5415 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5416 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005417 }
5418 Primitive::Type type = field->GetTypeAsPrimitiveType();
5419 bool is_primitive = type != Primitive::kPrimNot;
5420 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5421 strcmp("referent", field->GetName()) == 0) {
5422 is_primitive = true; // We lied above, so we have to expect a lie here.
5423 }
5424 MemberOffset offset = field->GetOffsetDuringLinking();
5425 if (is_primitive) {
5426 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5427 // Shuffled before references.
5428 size_t type_size = Primitive::ComponentSize(type);
5429 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5430 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5431 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5432 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5433 }
5434 } else {
5435 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5436 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5437 sizeof(mirror::HeapReference<mirror::Object>));
5438 }
5439 }
5440 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5441 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005442 return true;
5443}
5444
Vladimir Marko76649e82014-11-10 18:32:59 +00005445// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005446void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005447 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005448 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005449 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005450 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005451 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005452 // Compute reference offsets unless our superclass overflowed.
5453 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5454 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005455 if (num_reference_fields != 0u) {
5456 // All of the fields that contain object references are guaranteed be grouped in memory
5457 // starting at an appropriately aligned address after super class object data.
5458 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5459 sizeof(mirror::HeapReference<mirror::Object>));
5460 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005461 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005462 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005463 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005464 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005465 reference_offsets |= (0xffffffffu << start_bit) &
5466 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005467 }
5468 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005469 }
5470 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005471 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005472}
5473
Mathieu Chartier590fee92013-09-13 13:46:47 -07005474mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005475 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005476 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005477 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005478 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005479 return resolved;
5480 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005481 uint32_t utf16_length;
5482 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005483 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005484 dex_cache->SetResolvedString(string_idx, string);
5485 return string;
5486}
5487
Mathieu Chartier590fee92013-09-13 13:46:47 -07005488mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005489 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005490 StackHandleScope<2> hs(Thread::Current());
5491 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5492 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005493 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5494}
5495
5496mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005497 Handle<mirror::DexCache> dex_cache,
5498 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005499 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005500 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005501 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005502 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005503 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005504 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005505 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005506 // TODO: we used to throw here if resolved's class loader was not the
5507 // boot class loader. This was to permit different classes with the
5508 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005509 dex_cache->SetResolvedType(type_idx, resolved);
5510 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005511 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005512 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005513 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005514 StackHandleScope<1> hs(self);
5515 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005516 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005517 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005518 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005519 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005520 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005521 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005522 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005523 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005524 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005525 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005526 return resolved;
5527}
5528
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005529mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005530 Handle<mirror::DexCache> dex_cache,
5531 Handle<mirror::ClassLoader> class_loader,
5532 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005533 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005534 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005535 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005536 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005537 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005538 return resolved;
5539 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005540 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005541 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005542 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005543 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005544 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005545 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005546 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005547 // Scan using method_idx, this saves string compares but will only hit for matching dex
5548 // caches/files.
5549 switch (type) {
5550 case kDirect: // Fall-through.
5551 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005552 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005553 break;
5554 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005555 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005556 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005557 break;
5558 case kSuper: // Fall-through.
5559 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005560 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005561 break;
5562 default:
5563 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005564 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005565 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005566 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005567 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005568 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005569 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005570 switch (type) {
5571 case kDirect: // Fall-through.
5572 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005573 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005574 break;
5575 case kInterface:
5576 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005577 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005578 break;
5579 case kSuper: // Fall-through.
5580 case kVirtual:
5581 resolved = klass->FindVirtualMethod(name, signature);
5582 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005583 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005584 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005585 // If we found a method, check for incompatible class changes.
5586 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005587 // Be a good citizen and update the dex cache to speed subsequent calls.
5588 dex_cache->SetResolvedMethod(method_idx, resolved);
5589 return resolved;
5590 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005591 // If we had a method, it's an incompatible-class-change error.
5592 if (resolved != nullptr) {
5593 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5594 } else {
5595 // We failed to find the method which means either an access error, an incompatible class
5596 // change, or no such method. First try to find the method among direct and virtual methods.
5597 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5598 const Signature signature = dex_file.GetMethodSignature(method_id);
5599 switch (type) {
5600 case kDirect:
5601 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005602 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005603 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5604 // have had a resolved method before, which triggers the "true" branch above.
5605 break;
5606 case kInterface:
5607 case kVirtual:
5608 case kSuper:
5609 resolved = klass->FindDirectMethod(name, signature);
5610 break;
5611 }
5612
5613 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005614 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005615 if (resolved != nullptr && referrer.Get() != nullptr) {
5616 mirror::Class* methods_class = resolved->GetDeclaringClass();
5617 mirror::Class* referring_class = referrer->GetDeclaringClass();
5618 if (!referring_class->CanAccess(methods_class)) {
5619 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5620 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005621 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005622 } else if (!referring_class->CanAccessMember(methods_class,
5623 resolved->GetAccessFlags())) {
5624 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005625 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005626 }
5627 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005628 if (!exception_generated) {
5629 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5630 // interface methods and throw if we find the method there. If we find nothing, throw a
5631 // NoSuchMethodError.
5632 switch (type) {
5633 case kDirect:
5634 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005635 if (resolved != nullptr) {
5636 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5637 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005638 resolved = klass->FindInterfaceMethod(name, signature);
5639 if (resolved != nullptr) {
5640 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5641 } else {
5642 ThrowNoSuchMethodError(type, klass, name, signature);
5643 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005644 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005645 break;
5646 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005647 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005648 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5649 } else {
5650 resolved = klass->FindVirtualMethod(name, signature);
5651 if (resolved != nullptr) {
5652 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5653 } else {
5654 ThrowNoSuchMethodError(type, klass, name, signature);
5655 }
5656 }
5657 break;
5658 case kSuper:
5659 if (resolved != nullptr) {
5660 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005661 } else {
5662 ThrowNoSuchMethodError(type, klass, name, signature);
5663 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005664 break;
5665 case kVirtual:
5666 if (resolved != nullptr) {
5667 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5668 } else {
5669 resolved = klass->FindInterfaceMethod(name, signature);
5670 if (resolved != nullptr) {
5671 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5672 } else {
5673 ThrowNoSuchMethodError(type, klass, name, signature);
5674 }
5675 }
5676 break;
5677 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005678 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005679 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005680 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005681 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005682 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005683}
5684
Mathieu Chartier590fee92013-09-13 13:46:47 -07005685mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005686 Handle<mirror::DexCache> dex_cache,
5687 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005688 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005689 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005690 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005691 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005692 return resolved;
5693 }
5694 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005695 Thread* const self = Thread::Current();
5696 StackHandleScope<1> hs(self);
5697 Handle<mirror::Class> klass(
5698 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005699 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005700 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005701 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005702 }
5703
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005704 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005705 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005706 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005707 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005708 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005709
Andreas Gampe58a5af82014-07-31 16:23:49 -07005710 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005711 const char* name = dex_file.GetFieldName(field_id);
5712 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5713 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005714 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005715 } else {
5716 resolved = klass->FindInstanceField(name, type);
5717 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005718 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005719 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005720 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005721 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005722 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005723 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005724 return resolved;
5725}
5726
Brian Carlstromea46f952013-07-30 01:26:50 -07005727mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005728 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005729 Handle<mirror::DexCache> dex_cache,
5730 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005731 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005732 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005733 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005734 return resolved;
5735 }
5736 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005737 Thread* self = Thread::Current();
5738 StackHandleScope<1> hs(self);
5739 Handle<mirror::Class> klass(
5740 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005741 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005742 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005743 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005744 }
5745
Ian Rogersdfb325e2013-10-30 01:00:44 -07005746 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5747 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005748 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005749 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005750 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005751 dex_cache->SetResolvedField(field_idx, resolved);
5752 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005753 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005754 }
5755 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005756}
5757
Brian Carlstromea46f952013-07-30 01:26:50 -07005758const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005759 uint32_t* length) {
5760 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5761 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005762 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005763 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005764 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005765}
5766
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005767void ClassLinker::DumpAllClasses(int flags) {
5768 if (dex_cache_image_class_lookup_required_) {
5769 MoveImageClassesToClassTable();
5770 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005771 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5772 // 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 -08005773 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005774 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005775 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005776 for (GcRoot<mirror::Class>& it : class_table_) {
5777 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005778 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005779 }
5780
5781 for (size_t i = 0; i < all_classes.size(); ++i) {
5782 all_classes[i]->DumpClass(std::cerr, flags);
5783 }
5784}
5785
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005786static OatFile::OatMethod CreateOatMethod(const void* code, bool is_portable) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005787 CHECK_EQ(kUsePortableCompiler, is_portable);
5788 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005789 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5790 base -= sizeof(void*); // Move backward so that code_offset != 0.
5791 const uint32_t code_offset = sizeof(void*);
5792 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005793}
5794
5795bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5796 return (entry_point == GetPortableResolutionStub()) ||
5797 (portable_resolution_trampoline_ == entry_point);
5798}
5799
5800bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5801 return (entry_point == GetQuickResolutionStub()) ||
5802 (quick_resolution_trampoline_ == entry_point);
5803}
5804
5805bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5806 return (entry_point == GetPortableToInterpreterBridge());
5807 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5808}
5809
5810bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5811 return (entry_point == GetQuickToInterpreterBridge()) ||
5812 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5813}
5814
5815bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5816 return (entry_point == GetQuickGenericJniStub()) ||
5817 (quick_generic_jni_trampoline_ == entry_point);
5818}
5819
5820const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5821 return GetQuickGenericJniStub();
5822}
5823
5824void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5825 bool is_portable) const {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005826 OatFile::OatMethod oat_method = CreateOatMethod(method_code, is_portable);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005827 oat_method.LinkMethod(method);
5828 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5829 // Create bridges to transition between different kinds of compiled bridge.
5830 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5831 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5832 } else {
5833 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5834 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5835 method->SetIsPortableCompiled();
5836 }
5837}
5838
5839void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5840 if (!method->IsNative()) {
5841 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5842 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5843 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5844 } else {
5845 const void* quick_method_code = GetQuickGenericJniStub();
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005846 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, false);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005847 oat_method.LinkMethod(method);
5848 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5849 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5850 }
5851}
5852
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005853void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005854 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005855 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005856 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005857 MoveImageClassesToClassTable();
5858 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005859 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005860 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5861 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005862}
5863
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005864size_t ClassLinker::NumLoadedClasses() {
5865 if (dex_cache_image_class_lookup_required_) {
5866 MoveImageClassesToClassTable();
5867 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005868 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005869 // Only return non zygote classes since these are the ones which apps which care about.
5870 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005871}
5872
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005873pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005874 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005875}
5876
5877pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005878 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005879}
5880
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005881void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005882 DCHECK(!init_done_);
5883
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005884 DCHECK(klass != nullptr);
5885 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005886
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005887 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005888 DCHECK(class_roots != nullptr);
5889 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005890 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005891}
5892
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005893const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5894 static const char* class_roots_descriptors[] = {
5895 "Ljava/lang/Class;",
5896 "Ljava/lang/Object;",
5897 "[Ljava/lang/Class;",
5898 "[Ljava/lang/Object;",
5899 "Ljava/lang/String;",
5900 "Ljava/lang/DexCache;",
5901 "Ljava/lang/ref/Reference;",
5902 "Ljava/lang/reflect/ArtField;",
5903 "Ljava/lang/reflect/ArtMethod;",
5904 "Ljava/lang/reflect/Proxy;",
5905 "[Ljava/lang/String;",
5906 "[Ljava/lang/reflect/ArtField;",
5907 "[Ljava/lang/reflect/ArtMethod;",
5908 "Ljava/lang/ClassLoader;",
5909 "Ljava/lang/Throwable;",
5910 "Ljava/lang/ClassNotFoundException;",
5911 "Ljava/lang/StackTraceElement;",
5912 "Z",
5913 "B",
5914 "C",
5915 "D",
5916 "F",
5917 "I",
5918 "J",
5919 "S",
5920 "V",
5921 "[Z",
5922 "[B",
5923 "[C",
5924 "[D",
5925 "[F",
5926 "[I",
5927 "[J",
5928 "[S",
5929 "[Ljava/lang/StackTraceElement;",
5930 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005931 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5932 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005933
5934 const char* descriptor = class_roots_descriptors[class_root];
5935 CHECK(descriptor != nullptr);
5936 return descriptor;
5937}
5938
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005939std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5940 const {
5941 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005942 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005943}
5944
5945bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5946 const GcRoot<mirror::Class>& b) {
5947 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5948 return false;
5949 }
5950 std::string temp;
5951 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5952}
5953
5954std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5955 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005956 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005957}
5958
5959bool ClassLinker::ClassDescriptorHashEquals::operator()(
5960 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5961 if (a.Read()->GetClassLoader() != b.second) {
5962 return false;
5963 }
5964 return a.Read()->DescriptorEquals(b.first);
5965}
5966
5967bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5968 const char* descriptor) {
5969 return a.Read()->DescriptorEquals(descriptor);
5970}
5971
5972std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005973 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005974}
5975
Sebastien Hertz6963e442014-11-26 22:11:27 +01005976bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
5977 // Non-image methods don't use direct code pointer.
5978 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5979 return false;
5980 }
5981 if (m->IsPrivate()) {
5982 // The method can only be called inside its own oat file. Therefore it won't be called using
5983 // its direct code if the oat file has been compiled in PIC mode.
5984 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
5985 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
5986 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
5987 if (oat_dex_file == nullptr) {
5988 // No oat file: the method has not been compiled.
5989 return false;
5990 }
5991 const OatFile* oat_file = oat_dex_file->GetOatFile();
5992 return oat_file != nullptr && !oat_file->IsPic();
5993 } else {
5994 // The method can be called outside its own oat file. Therefore it won't be called using its
5995 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5996 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5997 for (const OatFile* oat_file : oat_files_) {
5998 if (!oat_file->IsPic()) {
5999 return true;
6000 }
6001 }
6002 return false;
6003 }
6004}
6005
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006006} // namespace art