blob: 52e6662fa933cf6768d238b1b3bff160e730027c [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>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070024#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070025#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070026
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080028#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010029#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080030#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080031#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000033#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080034#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070035#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070036#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070037#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
40#include "gc/heap.h"
41#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070042#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070043#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070044#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070045#include "leb128.h"
Ian Rogers1ff3c982014-08-12 02:30:58 -070046#include "method_helper-inl.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
708 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700709}
710
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700711const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700712 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800713 if (kIsDebugBuild) {
714 for (size_t i = 0; i < oat_files_.size(); ++i) {
715 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700716 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800717 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700718 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
719 oat_files_.push_back(oat_file);
720 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800721}
722
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700723OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
724 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700725 OatFile* oat_file = space->ReleaseOatFile();
726 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700727 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700728 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700729}
730
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100731const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800732 const char* dex_location = dex_file.GetLocation().c_str();
733 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100734 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800735}
736
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100737const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
738 const char* dex_location,
739 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700740 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100741 for (const OatFile* oat_file : oat_files_) {
742 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700743
744 if (oat_location != nullptr) {
745 if (oat_file->GetLocation() != oat_location) {
746 continue;
747 }
748 }
749
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700750 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800751 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700752 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100753 if (oat_dex_file != nullptr) {
754 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800755 }
756 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100757 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800758}
759
Calin Juravle621962a2014-09-02 15:53:55 +0100760
761// Loads all multi dex files from the given oat file returning true on success.
762//
763// Parameters:
764// oat_file - the oat file to load from
765// dex_location - the dex location used to generate the oat file
766// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
767// generated - whether or not the oat_file existed before or was just (re)generated
768// error_msgs - any error messages will be appended here
769// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
770static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
771 const char* dex_location,
772 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700773 bool generated,
774 std::vector<std::string>* error_msgs,
775 std::vector<const DexFile*>* dex_files) {
776 if (oat_file == nullptr) {
777 return false;
778 }
779
780 size_t old_size = dex_files->size(); // To rollback on error.
781
782 bool success = true;
783 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100784 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700785 const char* next_name = next_name_str.c_str();
786
Calin Juravle621962a2014-09-02 15:53:55 +0100787 uint32_t next_location_checksum;
788 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700789 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100790 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
791 // When i=0 the multidex name should be the same as the location name. We already have the
792 // checksum it so we don't need to recompute it.
793 if (dex_location_checksum == nullptr) {
794 next_location_checksum_pointer = nullptr;
795 } else {
796 next_location_checksum = *dex_location_checksum;
797 }
798 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700799 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100800 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700801 }
802
803 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
804
805 if (oat_dex_file == nullptr) {
806 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700807 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100808 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700809 oat_file->GetLocation().c_str());
810 error_msgs->push_back(error_msg);
811 }
812 break; // Not found, done.
813 }
814
815 // Checksum test. Test must succeed when generated.
816 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100817 if (next_location_checksum_pointer != nullptr) {
818 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700819 }
820
821 if (success) {
822 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
823 if (dex_file == nullptr) {
824 success = false;
825 error_msgs->push_back(error_msg);
826 } else {
827 dex_files->push_back(dex_file);
828 }
829 }
830
831 // When we generated the file, we expect success, or something is terribly wrong.
832 CHECK_EQ(false, generated && !success)
833 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100834 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700835 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
836 }
837
838 if (dex_files->size() == old_size) {
839 success = false; // We did not even find classes.dex
840 }
841
842 if (success) {
843 return true;
844 } else {
845 // Free all the dex files we have loaded.
846 auto it = dex_files->begin() + old_size;
847 auto it_end = dex_files->end();
848 for (; it != it_end; it++) {
849 delete *it;
850 }
851 dex_files->erase(dex_files->begin() + old_size, it_end);
852
853 return false;
854 }
855}
856
857// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
858// complicates the loading process, as we should not use an iterative loading process, because that
859// would register the oat file and dex files that come before the broken one. Instead, check all
860// multidex ahead of time.
861bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
862 std::vector<std::string>* error_msgs,
863 std::vector<const DexFile*>* dex_files) {
864 // 1) Check whether we have an open oat file.
865 // This requires a dex checksum, use the "primary" one.
866 uint32_t dex_location_checksum;
867 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
868 bool have_checksum = true;
869 std::string checksum_error_msg;
870 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100871 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700872 dex_location_checksum_pointer = nullptr;
873 have_checksum = false;
874 }
875
876 bool needs_registering = false;
877
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100878 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
879 dex_location_checksum_pointer);
880 std::unique_ptr<const OatFile> open_oat_file(
881 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700882
883 // 2) If we do not have an open one, maybe there's one on disk already.
884
885 // In case the oat file is not open, we play a locking game here so
886 // that if two different processes race to load and register or generate
887 // (or worse, one tries to open a partial generated file) we will be okay.
888 // This is actually common with apps that use DexClassLoader to work
889 // around the dex method reference limit and that have a background
890 // service running in a separate process.
891 ScopedFlock scoped_flock;
892
893 if (open_oat_file.get() == nullptr) {
894 if (oat_location != nullptr) {
895 // Can only do this if we have a checksum, else error.
896 if (!have_checksum) {
897 error_msgs->push_back(checksum_error_msg);
898 return false;
899 }
900
901 std::string error_msg;
902
903 // We are loading or creating one in the future. Time to set up the file lock.
904 if (!scoped_flock.Init(oat_location, &error_msg)) {
905 error_msgs->push_back(error_msg);
906 return false;
907 }
908
Alex Lighta59dd802014-07-02 16:28:08 -0700909 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700910 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
911 oat_location, &error_msg));
912
913 if (open_oat_file.get() == nullptr) {
914 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
915 dex_location, oat_location, error_msg.c_str());
916 VLOG(class_linker) << compound_msg;
917 error_msgs->push_back(compound_msg);
918 }
919 } else {
920 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100921 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700922 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
923 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100924 kRuntimeISA, error_msgs,
925 &obsolete_file_cleanup_failed));
926 // There's no point in going forward and eventually try to regenerate the
927 // file if we couldn't remove the obsolete one. Mostly likely we will fail
928 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100929 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
930 if (obsolete_file_cleanup_failed) {
931 return false;
932 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700933 }
934 needs_registering = true;
935 }
936
937 // 3) If we have an oat file, check all contained multidex files for our dex_location.
938 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100939 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
940 dex_location_checksum_pointer,
941 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700942 if (success) {
943 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
944 if (needs_registering) {
945 // We opened the oat file, so we must register it.
946 RegisterOatFile(oat_file);
947 }
Alex Light9dcc4572014-08-14 14:16:26 -0700948 // If the file isn't executable we failed patchoat but did manage to get the dex files.
949 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700950 } else {
951 if (needs_registering) {
952 // We opened it, delete it.
953 open_oat_file.reset();
954 } else {
955 open_oat_file.release(); // Do not delete open oat files.
956 }
957 }
958
959 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
960
961 // Need a checksum, fail else.
962 if (!have_checksum) {
963 error_msgs->push_back(checksum_error_msg);
964 return false;
965 }
966
967 // Look in cache location if no oat_location is given.
968 std::string cache_location;
969 if (oat_location == nullptr) {
970 // Use the dalvik cache.
971 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
972 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
973 oat_location = cache_location.c_str();
974 }
975
Alex Light64ad14d2014-08-19 14:23:13 -0700976 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700977 // Definitely need to lock now.
978 if (!scoped_flock.HasFile()) {
979 std::string error_msg;
980 if (!scoped_flock.Init(oat_location, &error_msg)) {
981 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700982 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700983 }
984 }
985
Alex Light64ad14d2014-08-19 14:23:13 -0700986 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +0100987 // Create the oat file.
988 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
989 oat_location, error_msgs));
990 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700991
992 // Failed, bail.
993 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +0100994 std::string error_msg;
995 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
996 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
997 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -0700998 return false;
999 }
1000
1001 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001002 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1003 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001004 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001005 if (success) {
1006 RegisterOatFile(open_oat_file.release());
1007 return true;
1008 } else {
1009 return false;
1010 }
1011}
1012
1013const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1014 uint32_t dex_location_checksum,
1015 const char* oat_location,
1016 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001017 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001018 !Runtime::Current()->IsCompiler(),
1019 error_msg));
1020 if (oat_file.get() == nullptr) {
1021 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1022 error_msg->c_str());
1023 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001024 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001025 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001026 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1027 if (image_space != nullptr) {
1028 const ImageHeader& image_header = image_space->GetImageHeader();
1029 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1030 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1031 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1032 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1033 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1034 actual_image_oat_checksum);
1035 return nullptr;
1036 }
1037
1038 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1039 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1040 if (expected_image_oat_offset != actual_image_oat_offset) {
1041 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1042 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1043 actual_image_oat_offset);
1044 return nullptr;
1045 }
1046 int32_t expected_patch_delta = image_header.GetPatchDelta();
1047 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1048 if (expected_patch_delta != actual_patch_delta) {
1049 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1050 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1051 return nullptr;
1052 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001053 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001054
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001055 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1056 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001057 if (oat_dex_file == nullptr) {
1058 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1059 dex_location);
1060 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001061 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001062 uint32_t expected_dex_checksum = dex_location_checksum;
1063 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1064 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001065 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1066 "found 0x%x", oat_location, expected_dex_checksum,
1067 actual_dex_checksum);
1068 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001069 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001070 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1071 if (dex_file.get() != nullptr) {
1072 return oat_file.release();
1073 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001074 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001075 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001076}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001077
Andreas Gampe833a4852014-05-21 18:46:59 -07001078const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1079 int fd, const char* oat_location,
1080 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001081 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001082 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001083 std::string error_msg;
1084 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001085 CHECK(!error_msg.empty());
1086 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001087 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001088 }
Igor Murashkin46774762014-10-22 11:37:02 -07001089 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001090 !Runtime::Current()->IsCompiler(),
1091 &error_msg));
1092 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001093 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1094 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001095 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001096 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001097 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001098
1099 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001100}
1101
Alex Light6e183f22014-07-18 14:57:04 -07001102bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1103 const InstructionSet instruction_set) {
1104 Runtime* runtime = Runtime::Current();
1105 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001106 if (image_space == nullptr) {
1107 return false;
1108 }
Alex Light6e183f22014-07-18 14:57:04 -07001109 uint32_t image_oat_checksum = 0;
1110 if (instruction_set == kRuntimeISA) {
1111 const ImageHeader& image_header = image_space->GetImageHeader();
1112 image_oat_checksum = image_header.GetOatChecksum();
1113 } else {
1114 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1115 image_space->GetImageLocation().c_str(), instruction_set));
1116 image_oat_checksum = image_header->GetOatChecksum();
1117 }
1118 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1119}
1120
1121bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1122 const InstructionSet instruction_set,
1123 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001124 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001125 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001126 if (image_space == nullptr) {
1127 *error_msg = "No image space for verification against";
1128 return false;
1129 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001130
1131 // If the requested instruction set is the same as the current runtime,
1132 // we can use the checksums directly. If it isn't, we'll have to read the
1133 // image header from the image for the right instruction set.
1134 uint32_t image_oat_checksum = 0;
1135 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001136 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001137 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001138 const ImageHeader& image_header = image_space->GetImageHeader();
1139 image_oat_checksum = image_header.GetOatChecksum();
1140 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001141 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001142 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001143 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001144 image_space->GetImageLocation().c_str(), instruction_set));
1145 image_oat_checksum = image_header->GetOatChecksum();
1146 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001147 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001148 }
1149 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001150 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1151
1152 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1153 if (!oat_file->IsPic()) {
1154 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1155 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1156 }
Alex Light6e183f22014-07-18 14:57:04 -07001157 if (!ret) {
1158 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1159 oat_file->GetLocation().c_str(),
1160 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1161 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1162 oat_file->GetOatHeader().GetImagePatchDelta(),
1163 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1164 }
1165 return ret;
1166}
1167
1168bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1169 const char* dex_location,
1170 uint32_t dex_location_checksum,
1171 const InstructionSet instruction_set,
1172 std::string* error_msg) {
1173 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1174 return false;
1175 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001176
Brian Carlstromf3632832014-05-20 15:36:53 -07001177 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1178 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001179 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001180 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1181 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001182 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001183 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001184 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001185 oat_dex_file_in->GetDexFileLocation().c_str(),
1186 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001187 }
1188 return false;
1189 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001190
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001191 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001192 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001193}
1194
Alex Lighta59dd802014-07-02 16:28:08 -07001195bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1196 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001197 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001198 std::string* error_msg) {
1199 CHECK(oat_file != nullptr);
1200 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001201 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001202 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001203 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1204 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1205 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001206 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001207 if (oat_dex_file == nullptr) {
1208 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001209 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001210 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001211 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001212 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001213 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001214 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001215 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001216 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001217 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001218 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001219 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001220 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001221 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001222 }
Alex Lighta59dd802014-07-02 16:28:08 -07001223 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001224}
1225
Andreas Gampe833a4852014-05-21 18:46:59 -07001226const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001227 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001228 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001229 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001230 std::vector<std::string>* error_msgs,
1231 bool* obsolete_file_cleanup_failed) {
1232 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001233 bool already_opened = false;
1234 std::string dex_location_str(dex_location);
1235 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1236 &already_opened,
1237 obsolete_file_cleanup_failed,
1238 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001239 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001240 if (oat_file.get() == nullptr) {
1241 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1242 dex_location));
1243 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001244 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001245 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1246 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001247 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1248 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001249 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001250 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001251 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001252 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001253 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1254 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1255 "dex location '%s'. Image checksum incorrect.",
1256 oat_file->GetLocation().c_str(), dex_location));
1257 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001258 } else {
1259 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001260 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001261}
1262
Brian Carlstromae826982011-11-09 01:33:42 -08001263const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001264 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001265 for (size_t i = 0; i < oat_files_.size(); i++) {
1266 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001267 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001268 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001269 return oat_file;
1270 }
1271 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001272 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001273}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001274
Alex Lighta59dd802014-07-02 16:28:08 -07001275const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1276 InstructionSet isa,
1277 bool *already_opened,
1278 bool *obsolete_file_cleanup_failed,
1279 std::vector<std::string>* error_msgs) {
1280 // Find out if we've already opened the file
1281 const OatFile* ret = nullptr;
1282 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1283 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1284 if (ret != nullptr) {
1285 *already_opened = true;
1286 return ret;
1287 }
1288
1289 std::string dalvik_cache;
1290 bool have_android_data = false;
1291 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001292 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001293 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001294 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001295 std::string cache_filename;
1296 if (have_dalvik_cache) {
1297 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1298 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1299 if (ret != nullptr) {
1300 *already_opened = true;
1301 return ret;
1302 }
1303 } else {
1304 // If we need to relocate we should just place odex back where it started.
1305 cache_filename = odex_filename;
1306 }
1307
1308 ret = nullptr;
1309
1310 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1311 //
1312 // Now we do the following:
1313 // 1) Try and open the odex version
1314 // 2) If present, checksum-verified & relocated correctly return it
1315 // 3) Close the odex version to free up its address space.
1316 // 4) Try and open the cache version
1317 // 5) If present, checksum-verified & relocated correctly return it
1318 // 6) Close the cache version to free up its address space.
1319 // 7) If we should relocate:
1320 // a) If we have opened and checksum-verified the odex version relocate it to
1321 // 'cache_filename' and return it
1322 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1323 // it. This should not happen often (I think only the run-test's will hit this case).
1324 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1325 // this point.
1326 // 9) Return nullptr
1327
1328 *already_opened = false;
1329 const Runtime* runtime = Runtime::Current();
1330 CHECK(runtime != nullptr);
1331 bool executable = !runtime->IsCompiler();
1332
1333 std::string odex_error_msg;
1334 bool should_patch_system = false;
1335 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001336 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001337 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001338 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001339 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001340 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001341 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001342 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001343 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001344 &odex_checksum_verified,
1345 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001346 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001347 } else {
1348 if (odex_checksum_verified) {
1349 // We can just relocate
1350 should_patch_system = true;
1351 odex_error_msg = "Image Patches are incorrect";
1352 }
1353 if (odex_oat_file.get() != nullptr) {
1354 have_system_odex = true;
1355 }
Alex Lighta59dd802014-07-02 16:28:08 -07001356 }
1357 }
1358
Alex Lighta59dd802014-07-02 16:28:08 -07001359 std::string cache_error_msg;
1360 bool should_patch_cache = false;
1361 bool cache_checksum_verified = false;
1362 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001363 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001364 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001365 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001366 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001367 &cache_checksum_verified,
1368 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001369 return cache_oat_file.release();
1370 } else if (cache_checksum_verified) {
1371 // We can just relocate
1372 should_patch_cache = true;
1373 cache_error_msg = "Image Patches are incorrect";
1374 }
1375 } else if (have_android_data) {
1376 // dalvik_cache does not exist but android data does. This means we should be able to create
1377 // it, so we should try.
1378 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1379 }
1380
1381 ret = nullptr;
1382 std::string error_msg;
1383 if (runtime->CanRelocate()) {
1384 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001385 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1386 if (space != nullptr) {
1387 const std::string& image_location = space->GetImageLocation();
1388 if (odex_checksum_verified && should_patch_system) {
1389 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1390 } else if (cache_checksum_verified && should_patch_cache) {
1391 CHECK(have_dalvik_cache);
1392 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1393 }
Alex Light84d76052014-08-22 17:49:35 -07001394 } else if (have_system_odex) {
1395 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001396 }
1397 }
1398 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1399 // implicitly: were able to fine where the cached version is but we were unable to use it,
1400 // either as a destination for relocation or to open a file. We should delete it if it is
1401 // there.
1402 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1403 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1404 "searching for dex file %s: %s",
1405 cache_filename.c_str(), dex_location.c_str(),
1406 strerror(errno));
1407 error_msgs->push_back(rm_error_msg);
1408 VLOG(class_linker) << rm_error_msg;
1409 // Let the caller know that we couldn't remove the obsolete file.
1410 // This is a good indication that further writes may fail as well.
1411 *obsolete_file_cleanup_failed = true;
1412 }
1413 }
1414 if (ret == nullptr) {
1415 VLOG(class_linker) << error_msg;
1416 error_msgs->push_back(error_msg);
1417 std::string relocation_msg;
1418 if (runtime->CanRelocate()) {
1419 relocation_msg = StringPrintf(" and relocation failed");
1420 }
1421 if (have_dalvik_cache && cache_checksum_verified) {
1422 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1423 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1424 cache_filename.c_str(), cache_error_msg.c_str(),
1425 relocation_msg.c_str());
1426 } else {
1427 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1428 "dalvik_cache availible)%s.", odex_filename.c_str(),
1429 odex_error_msg.c_str(), relocation_msg.c_str());
1430 }
1431 VLOG(class_linker) << error_msg;
1432 error_msgs->push_back(error_msg);
1433 }
1434 return ret;
1435}
1436
Alex Light9dcc4572014-08-14 14:16:26 -07001437const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1438 InstructionSet isa,
1439 std::string* error_msg) {
1440 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001441 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001442 if (output.get() == nullptr) {
1443 return nullptr;
1444 }
Alex Light84d76052014-08-22 17:49:35 -07001445 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1446 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001447 return output.release();
1448 } else {
1449 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1450 oat_path.c_str());
1451 return nullptr;
1452 }
1453}
1454
Alex Lighta59dd802014-07-02 16:28:08 -07001455const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1456 const std::string& output_oat,
1457 const std::string& image_location,
1458 InstructionSet isa,
1459 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001460 Runtime* runtime = Runtime::Current();
1461 DCHECK(runtime != nullptr);
1462 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001463 // We don't have an image space so there is no point in trying to patchoat.
1464 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1465 << "running without an image. Attempting to use oat file for interpretation.";
1466 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1467 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001468 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001469 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1470 // input_oat but make sure we only do interpretation on it's dex files.
1471 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1472 << "disabled. Attempting to use oat file for interpretation";
1473 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1474 }
Alex Lighta59dd802014-07-02 16:28:08 -07001475 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001476 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001477
1478 std::string isa_arg("--instruction-set=");
1479 isa_arg += GetInstructionSetString(isa);
1480 std::string input_oat_filename_arg("--input-oat-file=");
1481 input_oat_filename_arg += input_oat;
1482 std::string output_oat_filename_arg("--output-oat-file=");
1483 output_oat_filename_arg += output_oat;
1484 std::string patched_image_arg("--patched-image-location=");
1485 patched_image_arg += image_location;
1486
1487 std::vector<std::string> argv;
1488 argv.push_back(patchoat);
1489 argv.push_back(isa_arg);
1490 argv.push_back(input_oat_filename_arg);
1491 argv.push_back(output_oat_filename_arg);
1492 argv.push_back(patched_image_arg);
1493
1494 std::string command_line(Join(argv, ' '));
1495 LOG(INFO) << "Relocate Oat File: " << command_line;
1496 bool success = Exec(argv, error_msg);
1497 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001498 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001499 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001500 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001501 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1502 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001503 return output.release();
1504 } else if (output.get() != nullptr) {
1505 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1506 "but output file '%s' failed verifcation: %s",
1507 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1508 } else {
1509 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1510 "but was unable to open output file '%s': %s",
1511 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1512 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001513 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001514 // patchoat failed which means we probably don't have enough room to place the output oat file,
1515 // instead of failing we should just run the interpreter from the dex files in the input oat.
1516 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1517 << "for interpretation. patchoat failure was: " << *error_msg;
1518 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001519 } else {
1520 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1521 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1522 error_msg->c_str());
1523 }
1524 return nullptr;
1525}
1526
Andreas Gampe7ba64962014-10-23 11:37:40 -07001527bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001528 bool* checksum_verified,
1529 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001530 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001531 if (image_space == nullptr) {
1532 *error_msg = "No image space present";
1533 return false;
1534 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001535 uint32_t real_image_checksum;
1536 void* real_image_oat_offset;
1537 int32_t real_patch_delta;
1538 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001539 const ImageHeader& image_header = image_space->GetImageHeader();
1540 real_image_checksum = image_header.GetOatChecksum();
1541 real_image_oat_offset = image_header.GetOatDataBegin();
1542 real_patch_delta = image_header.GetPatchDelta();
1543 } else {
1544 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1545 image_space->GetImageLocation().c_str(), isa));
1546 real_image_checksum = image_header->GetOatChecksum();
1547 real_image_oat_offset = image_header->GetOatDataBegin();
1548 real_patch_delta = image_header->GetPatchDelta();
1549 }
1550
1551 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001552 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001553
1554 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1555 *checksum_verified = oat_image_checksum == real_image_checksum;
1556 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001557 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1558 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001559 }
1560
Andreas Gampe7ba64962014-10-23 11:37:40 -07001561 bool offset_verified;
1562 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001563
Andreas Gampe7ba64962014-10-23 11:37:40 -07001564 if (!oat_file->IsPic()) {
1565 // If an oat file is not PIC, we need to check that the image is at the expected location and
1566 // patched in the same way.
1567 void* oat_image_oat_offset =
1568 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1569 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1570 if (!offset_verified) {
1571 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1572 real_image_oat_offset, oat_image_oat_offset);
1573 }
1574
1575 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1576 patch_delta_verified = oat_patch_delta == real_patch_delta;
1577 if (!patch_delta_verified) {
1578 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1579 "received 0x%x)", real_patch_delta, oat_patch_delta);
1580 }
1581 } else {
1582 // If an oat file is PIC, we ignore offset and patching delta.
1583 offset_verified = true;
1584 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001585 }
1586
1587 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001588 if (!ret) {
1589 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001590 }
1591 return ret;
1592}
1593
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001594const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1595 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001596 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001597 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001598 return oat_file;
1599 }
1600
Igor Murashkin46774762014-10-22 11:37:02 -07001601 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001602 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001603}
1604
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001605static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001606 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001607 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1608
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001609 DCHECK(obj != nullptr);
1610 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001611
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001612 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001613 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001614 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001615 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers848871b2013-08-05 10:56:33 -07001616 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001617 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1618 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001619 }
1620 }
1621 }
1622}
1623
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001624void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001625 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001626 CHECK(!init_done_);
1627
Mathieu Chartier590fee92013-09-13 13:46:47 -07001628 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001629 gc::Heap* heap = Runtime::Current()->GetHeap();
1630 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001631 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001632 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001633 OatFile& oat_file = GetImageOatFile(space);
1634 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1635 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001636 const char* image_file_location = oat_file.GetOatHeader().
1637 GetStoreValueByKey(OatHeader::kImageLocationKey);
1638 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001639 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1640 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001641 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1642 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001643 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001644 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001645 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1646 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1647 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001648
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001649 StackHandleScope<1> hs(self);
1650 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1651 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1652 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001653 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001654
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001655 // Special case of setting up the String class early so that we can test arbitrary objects
1656 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001657 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001658
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001659 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001660 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001661 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001662 StackHandleScope<1> hs2(self);
1663 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001664 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001665 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1666 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001667 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001668 std::string error_msg;
1669 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001670 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001671 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001672 << " from within oat file " << oat_file.GetLocation()
1673 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001674 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001675 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001676
1677 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1678
1679 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001680 }
1681
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001682 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1683 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001684 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001685 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
1686 if (!Runtime::Current()->IsCompiler()) {
1687 // Compiler supports having an image with a different pointer size than the runtime. This
1688 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1689 // also use 32 bit dex2oat on a system with 64 bit apps.
1690 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1691 << sizeof(void*);
1692 }
1693 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1694 image_pointer_size_ = 4;
1695 } else {
1696 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1697 image_pointer_size_ = 8;
1698 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001699
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001700 // Set entry point to interpreter if in InterpretOnly mode.
1701 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001702 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001703 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001704 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001705
1706 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001707 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001708 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001709
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001710 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001711 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001712 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001713 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001714 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001715 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001716 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1717 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1718 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1719 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1720 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1721 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1722 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1723 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1724 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1725 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001726
Ian Rogers98379392014-02-24 16:53:16 -08001727 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001728
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001729 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001730}
1731
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001732void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1733 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1734 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001735 for (GcRoot<mirror::Class>& root : class_table_) {
1736 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1737 }
1738 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1739 root.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001740 }
1741 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001742 for (auto& root : new_class_roots_) {
1743 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
1744 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1745 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001746 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001747 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1748 // corresponding object. This is slow, but luckily for us, this may only happen with a
1749 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001750 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
1751 class_table_.Erase(it);
1752 class_table_.Insert(GcRoot<mirror::Class>(new_ref));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001753 }
1754 }
1755 }
1756 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1757 new_class_roots_.clear();
1758 }
1759 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1760 log_new_class_table_roots_ = true;
1761 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1762 log_new_class_table_roots_ = false;
1763 }
1764 // We deliberately ignore the class roots in the image since we
1765 // handle image roots by using the MS/CMS rescanning of dirty cards.
1766}
1767
Brian Carlstroma663ea52011-08-19 23:33:41 -07001768// Keep in sync with InitCallback. Anything we visit, we need to
1769// reinit references to when reinitializing a ClassLinker from a
1770// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001771void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001772 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001773 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001774 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001775 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001776 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001777 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1778 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001779 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001780 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1781 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001782 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001783 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001784 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001785 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1786 new_dex_cache_roots_.clear();
1787 }
1788 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1789 log_new_dex_caches_roots_ = true;
1790 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1791 log_new_dex_caches_roots_ = false;
1792 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001793 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001794 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001795 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1796 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001797 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001798 if (!find_array_class_cache_[i].IsNull()) {
1799 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001800 }
1801 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001802}
1803
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001804void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1805 if (dex_cache_image_class_lookup_required_) {
1806 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001807 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001808 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001809 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001810 for (GcRoot<mirror::Class>& root : class_table_) {
1811 if (!visitor(root.Read(), arg)) {
1812 return;
1813 }
1814 }
1815 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1816 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001817 return;
1818 }
1819 }
1820}
1821
Ian Rogersdbf3be02014-08-29 15:40:08 -07001822static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001823 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001824 classes->insert(c);
1825 return true;
1826}
1827
Ian Rogersdbf3be02014-08-29 15:40:08 -07001828struct GetClassesVisitorArrayArg {
1829 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1830 int32_t index;
1831 bool success;
1832};
1833
1834static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1835 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1836 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1837 if (arg->index < (*arg->classes)->GetLength()) {
1838 (*arg->classes)->Set(arg->index, c);
1839 arg->index++;
1840 return true;
1841 } else {
1842 arg->success = false;
1843 return false;
1844 }
1845}
1846
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001847void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001848 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1849 // is avoiding duplicates.
1850 if (!kMovingClasses) {
1851 std::set<mirror::Class*> classes;
1852 VisitClasses(GetClassesVisitorSet, &classes);
1853 for (mirror::Class* klass : classes) {
1854 if (!visitor(klass, arg)) {
1855 return;
1856 }
1857 }
1858 } else {
1859 Thread* self = Thread::Current();
1860 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001861 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001862 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1863 GetClassesVisitorArrayArg local_arg;
1864 local_arg.classes = &classes;
1865 local_arg.success = false;
1866 // We size the array assuming classes won't be added to the class table during the visit.
1867 // If this assumption fails we iterate again.
1868 while (!local_arg.success) {
1869 size_t class_table_size;
1870 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001871 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001872 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001873 }
1874 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1875 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1876 classes.Assign(
1877 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1878 CHECK(classes.Get() != nullptr); // OOME.
1879 local_arg.index = 0;
1880 local_arg.success = true;
1881 VisitClasses(GetClassesVisitorArray, &local_arg);
1882 }
1883 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1884 // If the class table shrank during creation of the clases array we expect null elements. If
1885 // the class table grew then the loop repeats. If classes are created after the loop has
1886 // finished then we don't visit.
1887 mirror::Class* klass = classes->Get(i);
1888 if (klass != nullptr && !visitor(klass, arg)) {
1889 return;
1890 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001891 }
1892 }
1893}
1894
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001895ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001896 mirror::Class::ResetClass();
1897 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001898 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001899 mirror::ArtField::ResetClass();
1900 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001901 mirror::BooleanArray::ResetArrayClass();
1902 mirror::ByteArray::ResetArrayClass();
1903 mirror::CharArray::ResetArrayClass();
1904 mirror::DoubleArray::ResetArrayClass();
1905 mirror::FloatArray::ResetArrayClass();
1906 mirror::IntArray::ResetArrayClass();
1907 mirror::LongArray::ResetArrayClass();
1908 mirror::ShortArray::ResetArrayClass();
1909 mirror::Throwable::ResetClass();
1910 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001911 STLDeleteElements(&boot_class_path_);
1912 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001913}
1914
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001915mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001916 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001917 StackHandleScope<16> hs(self);
1918 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1919 Handle<mirror::DexCache> dex_cache(
1920 hs.NewHandle(down_cast<mirror::DexCache*>(
1921 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1922 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001923 if (dex_cache.Get() == nullptr) {
1924 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001925 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001926 Handle<mirror::String>
1927 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001928 if (location.Get() == nullptr) {
1929 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001930 }
Ian Rogers700a4022014-05-19 16:49:03 -07001931 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001932 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001933 if (strings.Get() == nullptr) {
1934 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001935 }
Ian Rogers700a4022014-05-19 16:49:03 -07001936 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001937 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001938 if (types.Get() == nullptr) {
1939 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001940 }
Ian Rogers700a4022014-05-19 16:49:03 -07001941 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001942 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001943 if (methods.Get() == nullptr) {
1944 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001945 }
Ian Rogers700a4022014-05-19 16:49:03 -07001946 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001947 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001948 if (fields.Get() == nullptr) {
1949 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001950 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001951 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1952 fields.Get());
1953 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001954}
1955
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001956mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001957 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001958 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001959 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001960 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001961 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001962 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1963 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001964 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001965 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001966 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001967 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001968 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001969}
1970
Ian Rogers6fac4472014-02-25 17:01:10 -08001971mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001972 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001973}
1974
Brian Carlstromea46f952013-07-30 01:26:50 -07001975mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001976 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001977 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001978}
1979
Brian Carlstromea46f952013-07-30 01:26:50 -07001980mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001981 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001982 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001983}
1984
Mathieu Chartier590fee92013-09-13 13:46:47 -07001985mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1986 Thread* self, size_t length) {
1987 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1988 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001989}
1990
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001991mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1992 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001993 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001994
1995 // For temporary classes we must wait for them to be retired.
1996 if (init_done_ && klass->IsTemp()) {
1997 CHECK(!klass->IsResolved());
1998 if (klass->IsErroneous()) {
1999 ThrowEarlierClassFailure(klass);
2000 return nullptr;
2001 }
2002 StackHandleScope<1> hs(self);
2003 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2004 ObjectLock<mirror::Class> lock(self, h_class);
2005 // Loop and wait for the resolving thread to retire this class.
2006 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2007 lock.WaitIgnoringInterrupts();
2008 }
2009 if (h_class->IsErroneous()) {
2010 ThrowEarlierClassFailure(h_class.Get());
2011 return nullptr;
2012 }
2013 CHECK(h_class->IsRetired());
2014 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002015 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2016 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002017 }
2018
Brian Carlstromaded5f72011-10-07 17:15:04 -07002019 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002020 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002021 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002022 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2023 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002024 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002025 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2026 ThrowClassCircularityError(h_class.Get());
2027 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002028 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002029 }
2030 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002031 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002032 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002033 }
2034 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002035
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002036 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002037 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002038 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002039 }
2040 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002041 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002042 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002043 return klass;
2044}
2045
Ian Rogers68b56852014-08-29 20:19:11 -07002046typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2047
2048// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002049ClassPathEntry FindInClassPath(const char* descriptor,
2050 size_t hash, const std::vector<const DexFile*>& class_path) {
2051 for (const DexFile* dex_file : class_path) {
2052 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002053 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002054 return ClassPathEntry(dex_file, dex_class_def);
2055 }
2056 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002057 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002058}
2059
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002060mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2061 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002062 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002063 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002064 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002065 if (class_loader->GetClass() !=
2066 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2067 class_loader->GetParent()->GetClass() !=
2068 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2069 return nullptr;
2070 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002071 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002072 // Check if this would be found in the parent boot class loader.
2073 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002074 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002075 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002076 // May return null if resolution on another thread fails.
2077 klass = EnsureResolved(self, descriptor, klass);
2078 } else {
2079 // May OOME.
2080 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2081 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002082 }
Ian Rogers32427292014-11-19 14:05:21 -08002083 if (klass == nullptr) {
2084 CHECK(self->IsExceptionPending()) << descriptor;
2085 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002086 }
Ian Rogers32427292014-11-19 14:05:21 -08002087 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002088 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002089 // Handle as if this is the child PathClassLoader.
2090 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002091 StackHandleScope<3> hs(self);
2092 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2093 // We need to get the DexPathList and loop through it.
2094 Handle<mirror::ArtField> cookie_field =
2095 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2096 Handle<mirror::ArtField> dex_file_field =
2097 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002098 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002099 mirror::Object* dex_path_list =
2100 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2101 GetObject(class_loader.Get());
2102 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2103 cookie_field.Get() != nullptr) {
2104 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2105 mirror::Object* dex_elements_obj =
2106 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2107 GetObject(dex_path_list);
2108 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2109 // at the mCookie which is a DexFile vector.
2110 if (dex_elements_obj != nullptr) {
2111 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2112 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2113 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2114 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2115 if (element == nullptr) {
2116 // Should never happen, fall back to java code to throw a NPE.
2117 break;
2118 }
2119 mirror::Object* dex_file = dex_file_field->GetObject(element);
2120 if (dex_file != nullptr) {
2121 const uint64_t cookie = cookie_field->GetLong(dex_file);
2122 auto* dex_files =
2123 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2124 if (dex_files == nullptr) {
2125 // This should never happen so log a warning.
2126 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2127 break;
2128 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002129 for (const DexFile* cp_dex_file : *dex_files) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002130 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002131 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002132 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002133 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2134 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002135 if (klass == nullptr) {
2136 CHECK(self->IsExceptionPending()) << descriptor;
2137 self->ClearException();
2138 return nullptr;
2139 }
2140 return klass;
2141 }
2142 }
2143 }
2144 }
2145 }
2146 }
Ian Rogers32427292014-11-19 14:05:21 -08002147 self->AssertNoPendingException();
2148 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002149 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002150}
2151
Ian Rogers98379392014-02-24 16:53:16 -08002152mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002153 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002154 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002155 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002156 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002157 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002158 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2159 // for primitive classes that aren't backed by dex files.
2160 return FindPrimitiveClass(descriptor[0]);
2161 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002162 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002163 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002164 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002165 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002166 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002167 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002168 // Class is not yet loaded.
2169 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002170 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002171 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002172 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002173 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002174 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002175 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002176 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002177 } else {
2178 // The boot class loader is searched ahead of the application class loader, failures are
2179 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2180 // trigger the chaining with a proper stack trace.
2181 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2182 self->SetException(ThrowLocation(), pre_allocated);
2183 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002184 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002185 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002186 // First try with the bootstrap class loader.
2187 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002188 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002189 if (klass != nullptr) {
2190 return EnsureResolved(self, descriptor, klass);
2191 }
2192 }
Ian Rogers63557452014-06-04 16:57:15 -07002193 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2194 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002195 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002196 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002197 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002198 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002199 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002200 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002201 const std::vector<const DexFile*>* class_path;
2202 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002203 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002204 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002205 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002206 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2207 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002208 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002209 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002210 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002211 } else {
2212 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2213 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2214 self->SetException(ThrowLocation(), pre_allocated);
2215 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002216 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002217 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002218 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002219 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2220 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002221 if (cp_klass != nullptr) {
2222 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002223 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002224 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002225 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002226 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002227 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002228 {
2229 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002230 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2231 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002232 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002233 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002234 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002235 }
Ian Rogers68b56852014-08-29 20:19:11 -07002236 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002237 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2238 WellKnownClasses::java_lang_ClassLoader_loadClass,
2239 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002240 }
Ian Rogers98379392014-02-24 16:53:16 -08002241 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002242 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002243 return nullptr;
2244 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002245 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002246 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002247 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002248 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002249 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002250 // success, return mirror::Class*
2251 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002252 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002253 }
Ian Rogers07140832014-09-30 15:43:59 -07002254 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002255}
2256
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002257mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002258 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002259 const DexFile& dex_file,
2260 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002261 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002262 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002263
Brian Carlstromaded5f72011-10-07 17:15:04 -07002264 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002265 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002266 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002267 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002268 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002269 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002270 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002271 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002272 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002273 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2274 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002275 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002276 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002277 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002278 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002279 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002280 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002281 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002282 }
2283
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002284 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002285 // Allocate a class with the status of not ready.
2286 // Interface object should get the right size here. Regular class will
2287 // figure out the right size later and be replaced with one of the right
2288 // size when the class becomes resolved.
2289 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002290 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002291 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002292 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002293 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002294 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002295 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002296 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002297 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002298 if (self->IsExceptionPending()) {
2299 // An exception occured during load, set status to erroneous while holding klass' lock in case
2300 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002301 if (!klass->IsErroneous()) {
2302 klass->SetStatus(mirror::Class::kStatusError, self);
2303 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002304 return nullptr;
2305 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002306 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002307
Mathieu Chartier590fee92013-09-13 13:46:47 -07002308 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002309 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002310 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002311 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2312 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002313 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002314 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002315
Brian Carlstromaded5f72011-10-07 17:15:04 -07002316 // Finish loading (if necessary) by finding parents
2317 CHECK(!klass->IsLoaded());
2318 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2319 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002320 if (!klass->IsErroneous()) {
2321 klass->SetStatus(mirror::Class::kStatusError, self);
2322 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002323 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002324 }
2325 CHECK(klass->IsLoaded());
2326 // Link the class (if necessary)
2327 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002328 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002329 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002330
2331 mirror::Class* new_class = nullptr;
2332 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002333 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002334 if (!klass->IsErroneous()) {
2335 klass->SetStatus(mirror::Class::kStatusError, self);
2336 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002337 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002338 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002339 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002340 CHECK(new_class != nullptr) << descriptor;
2341 CHECK(new_class->IsResolved()) << descriptor;
2342
2343 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002344
2345 /*
2346 * We send CLASS_PREPARE events to the debugger from here. The
2347 * definition of "preparation" is creating the static fields for a
2348 * class and initializing them to the standard default values, but not
2349 * executing any code (that comes later, during "initialization").
2350 *
2351 * We did the static preparation in LinkClass.
2352 *
2353 * The class has been prepared and resolved but possibly not yet verified
2354 * at this point.
2355 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002356 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002357
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002358 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002359}
2360
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002361uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2362 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002363 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002364 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002365 size_t num_8 = 0;
2366 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002367 size_t num_32 = 0;
2368 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002369 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002370 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2371 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002372 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002373 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002374 switch (c) {
2375 case 'L':
2376 case '[':
2377 num_ref++;
2378 break;
2379 case 'J':
2380 case 'D':
2381 num_64++;
2382 break;
2383 case 'I':
2384 case 'F':
2385 num_32++;
2386 break;
2387 case 'S':
2388 case 'C':
2389 num_16++;
2390 break;
2391 case 'B':
2392 case 'Z':
2393 num_8++;
2394 break;
2395 default:
2396 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002397 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002398 }
2399 }
2400 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002401 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002402}
2403
Ian Rogers97b52f82014-08-14 11:34:07 -07002404OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2405 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002406 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002407 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2408 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002409 *found = false;
2410 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002411 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002412 *found = true;
2413 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002414}
2415
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002416static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2417 uint32_t method_idx) {
2418 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002419 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002420 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002421 ClassDataItemIterator it(dex_file, class_data);
2422 // Skip fields
2423 while (it.HasNextStaticField()) {
2424 it.Next();
2425 }
2426 while (it.HasNextInstanceField()) {
2427 it.Next();
2428 }
2429 // Process methods
2430 size_t class_def_method_index = 0;
2431 while (it.HasNextDirectMethod()) {
2432 if (it.GetMemberIndex() == method_idx) {
2433 return class_def_method_index;
2434 }
2435 class_def_method_index++;
2436 it.Next();
2437 }
2438 while (it.HasNextVirtualMethod()) {
2439 if (it.GetMemberIndex() == method_idx) {
2440 return class_def_method_index;
2441 }
2442 class_def_method_index++;
2443 it.Next();
2444 }
2445 DCHECK(!it.HasNext());
2446 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002447 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002448}
2449
Ian Rogers97b52f82014-08-14 11:34:07 -07002450const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002451 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002452 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002453 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002454 size_t oat_method_index;
2455 if (method->IsStatic() || method->IsDirect()) {
2456 // Simple case where the oat method index was stashed at load time.
2457 oat_method_index = method->GetMethodIndex();
2458 } else {
2459 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2460 // by search for its position in the declared virtual methods.
2461 oat_method_index = declaring_class->NumDirectMethods();
2462 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002463 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002464 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002465 // Check method index instead of identity in case of duplicate method definitions.
2466 if (method->GetDexMethodIndex() ==
2467 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002468 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002469 break;
2470 }
Ian Rogersf320b632012-03-13 18:47:47 -07002471 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002472 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002473 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2474 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002475 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002476 DCHECK_EQ(oat_method_index,
2477 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002478 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002479 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002480 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2481 declaring_class->GetDexClassDefIndex(),
2482 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002483 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002484 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002485 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002486 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002487}
2488
2489// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002490const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002491 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002492 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002493 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002494 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002495 bool found;
2496 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002497 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002498 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002499 result = oat_method.GetQuickCode();
2500 }
2501
Ian Rogersef7d42f2014-01-06 12:55:46 -08002502 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002503 if (method->IsNative()) {
2504 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002505 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002506 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002507 // No code? Do we expect portable code?
2508 result = GetQuickToPortableBridge();
2509 } else {
2510 // No code? You must mean to go into the interpreter.
2511 result = GetQuickToInterpreterBridge();
2512 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002513 }
2514 return result;
TDYa12785321912012-04-01 15:24:56 -07002515}
2516
Ian Rogersef7d42f2014-01-06 12:55:46 -08002517const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2518 bool* have_portable_code) {
2519 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2520 *have_portable_code = false;
2521 if (method->IsProxyMethod()) {
2522 return GetPortableProxyInvokeHandler();
2523 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002524 bool found;
2525 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002526 const void* result = nullptr;
2527 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002528 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002529 result = oat_method.GetPortableCode();
2530 quick_code = oat_method.GetQuickCode();
2531 }
2532
Ian Rogersef7d42f2014-01-06 12:55:46 -08002533 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002534 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002535 // No code? You must mean to go into the interpreter.
2536 result = GetPortableToInterpreterBridge();
2537 } else {
2538 // No code? But there's quick code, so use a bridge.
2539 result = GetPortableToQuickBridge();
2540 }
2541 } else {
2542 *have_portable_code = true;
2543 }
2544 return result;
2545}
2546
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002547const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2548 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2549 return nullptr;
2550 }
2551 bool found;
2552 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2553 return found ? oat_method.GetQuickCode() : nullptr;
2554}
2555
2556const void* ClassLinker::GetOatMethodPortableCodeFor(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.GetPortableCode() : nullptr;
2563}
2564
Ian Rogersef7d42f2014-01-06 12:55:46 -08002565const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2566 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002567 bool found;
2568 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2569 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002570 return nullptr;
2571 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002572 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002573 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002574}
2575
2576const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2577 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002578 bool found;
2579 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2580 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002581 return nullptr;
2582 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002583 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002584 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002585}
2586
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002587// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002588static bool NeedsInterpreter(
2589 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2590 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002591 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002592 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002593 // May return true for native code, in the case of generic JNI
2594 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002595 return true;
2596 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002597#ifdef ART_SEA_IR_MODE
2598 ScopedObjectAccess soa(Thread::Current());
2599 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2600 LOG(INFO) << "Found " << PrettyMethod(method);
2601 return false;
2602 }
2603#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002604 // If interpreter mode is enabled, every method (except native and proxy) must
2605 // be run with interpreter.
2606 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2607 !method->IsNative() && !method->IsProxyMethod();
2608}
2609
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002610void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002611 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002612 if (klass->NumDirectMethods() == 0) {
2613 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002614 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002615 Runtime* runtime = Runtime::Current();
2616 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002617 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2618 return; // OAT file unavailable.
2619 }
Ian Rogers19846512012-02-24 11:42:47 -08002620 }
Alex Light64ad14d2014-08-19 14:23:13 -07002621
Mathieu Chartierf8322842014-05-16 10:59:25 -07002622 const DexFile& dex_file = klass->GetDexFile();
2623 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002624 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002625 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002626 // There should always be class data if there were direct methods.
2627 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002628 ClassDataItemIterator it(dex_file, class_data);
2629 // Skip fields
2630 while (it.HasNextStaticField()) {
2631 it.Next();
2632 }
2633 while (it.HasNextInstanceField()) {
2634 it.Next();
2635 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002636 bool has_oat_class;
2637 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2638 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002639 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002640 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002641 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002642 if (!method->IsStatic()) {
2643 // Only update static methods.
2644 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002645 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002646 const void* portable_code = nullptr;
2647 const void* quick_code = nullptr;
2648 if (has_oat_class) {
2649 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2650 portable_code = oat_method.GetPortableCode();
2651 quick_code = oat_method.GetQuickCode();
2652 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002653 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2654 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002655 if (enter_interpreter) {
2656 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002657 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002658 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002659 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002660 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002661 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002662 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002663 quick_code = GetQuickToInterpreterBridge();
2664 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002665 } else {
2666 if (portable_code == nullptr) {
2667 portable_code = GetPortableToQuickBridge();
2668 } else {
2669 have_portable_code = true;
2670 }
2671 if (quick_code == nullptr) {
2672 quick_code = GetQuickToPortableBridge();
2673 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002674 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002675 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2676 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002677 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002678 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002679}
2680
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002681void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002682 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002683 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002684 Runtime* runtime = Runtime::Current();
2685 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002686 // The following code only applies to a non-compiler runtime.
2687 return;
2688 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002689 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002690 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2691 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002692 if (oat_class != nullptr) {
2693 // Every kind of method should at least get an invoke stub from the oat_method.
2694 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002695 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002696 oat_method.LinkMethod(method.Get());
2697 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002698
Jeff Hao16743632013-05-08 10:59:04 -07002699 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002700 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002701 method->GetEntryPointFromQuickCompiledCode(),
2702 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002703 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002704 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002705 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002706 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002707 }
2708
Brian Carlstrom92827a52011-10-10 15:50:01 -07002709 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002710 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2711 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002712 return;
2713 }
Ian Rogers19846512012-02-24 11:42:47 -08002714
Ian Rogersef7d42f2014-01-06 12:55:46 -08002715 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002716 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002717 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002718 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2719 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002720 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2721 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002722 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002723 if (!method->IsNative()) {
2724 // Set entry point from compiled code if there's no code or in interpreter only mode.
2725 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2726 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2727 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002728 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002729 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2730 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002731 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2732 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2733 have_portable_code = true;
2734 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2735 } else {
2736 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2737 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002738 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002739
Ian Rogers62d6c772013-02-27 08:32:07 -08002740 if (method->IsNative()) {
2741 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002742 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002743
2744 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002745 // We have a native method here without code. Then it should have either the generic JNI
2746 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2747 // TODO: this doesn't handle all the cases where trampolines may be installed.
2748 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2749 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002750 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002751 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002752
Ian Rogers62d6c772013-02-27 08:32:07 -08002753 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002754 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002755 method->GetEntryPointFromQuickCompiledCode(),
2756 method->GetEntryPointFromPortableCompiledCode(),
2757 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002758}
2759
Fred Shih37f05ef2014-07-16 18:38:08 -07002760
Fred Shih37f05ef2014-07-16 18:38:08 -07002761
Ian Rogers7b078e82014-09-10 14:44:24 -07002762void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002763 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002764 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002765 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002766 CHECK(klass.Get() != nullptr);
2767 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002768 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002769 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002770 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002771
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002772 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002773 if (kUseBakerOrBrooksReadBarrier) {
2774 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002775 }
Andreas Gampe51829322014-08-25 15:05:04 -07002776 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002777 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002778 klass->SetAccessFlags(access_flags);
2779 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002780 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002781 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002782
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002783 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002784 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002785 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002786
Ian Rogers13735952014-10-08 12:43:28 -07002787 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002788 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002789 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002790 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002791
Ian Rogers97b52f82014-08-14 11:34:07 -07002792
2793 bool has_oat_class = false;
2794 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2795 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2796 &has_oat_class);
2797 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002798 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002799 }
2800 }
2801 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002802 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002803 }
2804}
2805
Ian Rogers7b078e82014-09-10 14:44:24 -07002806void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002807 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002808 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002809 const OatFile::OatClass* oat_class) {
2810 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002811 ClassDataItemIterator it(dex_file, class_data);
2812 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002813 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002814 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002815 CHECK(self->IsExceptionPending()); // OOME.
2816 return;
2817 }
2818 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002819 }
2820 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002821 mirror::ObjectArray<mirror::ArtField>* fields =
2822 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002823 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002824 CHECK(self->IsExceptionPending()); // OOME.
2825 return;
2826 }
2827 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002828 }
2829 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002830 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002831 StackHandleScope<1> hs(self);
2832 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002833 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002834 CHECK(self->IsExceptionPending()); // OOME.
2835 return;
2836 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002837 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002838 LoadField(dex_file, it, klass, sfield);
2839 }
2840 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002841 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002842 StackHandleScope<1> hs(self);
2843 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002844 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002845 CHECK(self->IsExceptionPending()); // OOME.
2846 return;
2847 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002848 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002849 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002850 }
2851
Ian Rogers0571d352011-11-03 19:51:38 -07002852 // Load methods.
2853 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002854 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002855 mirror::ObjectArray<mirror::ArtMethod>* directs =
2856 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002857 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002858 CHECK(self->IsExceptionPending()); // OOME.
2859 return;
2860 }
2861 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002862 }
Ian Rogers0571d352011-11-03 19:51:38 -07002863 if (it.NumVirtualMethods() != 0) {
2864 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002865 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2866 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002867 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002868 CHECK(self->IsExceptionPending()); // OOME.
2869 return;
2870 }
2871 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002872 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002873 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002874 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2875 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002876 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002877 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002878 StackHandleScope<1> hs(self);
2879 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002880 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002881 CHECK(self->IsExceptionPending()); // OOME.
2882 return;
2883 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002884 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002885 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002886 uint32_t it_method_index = it.GetMemberIndex();
2887 if (last_dex_method_index == it_method_index) {
2888 // duplicate case
2889 method->SetMethodIndex(last_class_def_method_index);
2890 } else {
2891 method->SetMethodIndex(class_def_method_index);
2892 last_dex_method_index = it_method_index;
2893 last_class_def_method_index = class_def_method_index;
2894 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002895 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002896 }
2897 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002898 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002899 StackHandleScope<1> hs(self);
2900 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002901 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002902 CHECK(self->IsExceptionPending()); // OOME.
2903 return;
2904 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002905 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002906 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002907 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002908 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002909 }
2910 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002911}
2912
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002913void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002914 Handle<mirror::Class> klass,
2915 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002916 uint32_t field_idx = it.GetMemberIndex();
2917 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002918 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002919 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002920}
2921
Brian Carlstromea46f952013-07-30 01:26:50 -07002922mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002923 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002924 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002925 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002926 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002927 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002928
Brian Carlstromea46f952013-07-30 01:26:50 -07002929 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002930 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002931 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002932 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002933 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002934 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002935
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002936 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002937 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002938 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002939 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002940
Ian Rogers19846512012-02-24 11:42:47 -08002941 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002942 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002943
Andreas Gampe51829322014-08-25 15:05:04 -07002944 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002945
Ian Rogersdfb325e2013-10-30 01:00:44 -07002946 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002947 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002948 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2949 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002950 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002951 klass->SetFinalizable();
2952 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002953 std::string temp;
2954 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002955 // The Enum class declares a "final" finalize() method to prevent subclasses from
2956 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2957 // subclasses, so we exclude it here.
2958 // We also want to avoid setting the flag on Object, where we know that finalize() is
2959 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002960 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2961 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002962 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002963 }
2964 }
2965 }
2966 } else if (method_name[0] == '<') {
2967 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002968 bool is_init = (strcmp("<init>", method_name) == 0);
2969 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002970 if (UNLIKELY(!is_init && !is_clinit)) {
2971 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2972 } else {
2973 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2974 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002975 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002976 access_flags |= kAccConstructor;
2977 }
2978 }
2979 }
2980 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002981
Mathieu Chartier66f19252012-09-18 08:57:04 -07002982 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002983}
2984
Ian Rogers7b078e82014-09-10 14:44:24 -07002985void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002986 StackHandleScope<1> hs(self);
2987 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002988 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2989 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002990 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002991}
2992
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002993void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002994 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002995 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002996 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002997 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002998}
2999
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003000bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003001 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07003002 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003003 mirror::DexCache* dex_cache = GetDexCache(i);
3004 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08003005 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003006 }
3007 }
3008 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003009}
3010
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003011bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003012 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003013 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003014}
3015
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003016void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003017 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003018 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003019 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003020 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3021 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003022 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003023 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003024 if (log_new_dex_caches_roots_) {
3025 // TODO: This is not safe if we can remove dex caches.
3026 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3027 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003028}
3029
Brian Carlstromaded5f72011-10-07 17:15:04 -07003030void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003031 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003032 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003033 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003034 if (IsDexFileRegisteredLocked(dex_file)) {
3035 return;
3036 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003037 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003038 // Don't alloc while holding the lock, since allocation may need to
3039 // suspend all threads and another thread may need the dex_lock_ to
3040 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003041 StackHandleScope<1> hs(self);
3042 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003043 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3044 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003045 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003046 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003047 if (IsDexFileRegisteredLocked(dex_file)) {
3048 return;
3049 }
3050 RegisterDexFileLocked(dex_file, dex_cache);
3051 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003052}
3053
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003054void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003055 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003056 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003057 RegisterDexFileLocked(dex_file, dex_cache);
3058}
3059
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003060mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003061 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003062 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003063 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003064 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003065 if (dex_cache->GetDexFile() == &dex_file) {
3066 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003067 }
3068 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003069 // Search matching by location name.
3070 std::string location(dex_file.GetLocation());
3071 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003072 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003073 if (dex_cache->GetDexFile()->GetLocation() == location) {
3074 return dex_cache;
3075 }
3076 }
3077 // Failure, dump diagnostic and abort.
3078 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003079 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003080 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3081 }
3082 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003083 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003084}
3085
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003086void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003087 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003088 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003089 mirror::DexCache* dex_cache = GetDexCache(i);
3090 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003091 }
3092}
3093
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003094mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003095 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003096 if (UNLIKELY(klass == nullptr)) {
3097 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003098 }
3099 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003100}
3101
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003102mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3103 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003104 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003105 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003106 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003107 StackHandleScope<1> hs(self);
3108 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003109 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003110 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003111 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003112 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3113 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003114 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3115 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003116 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003117 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003118}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003119
Brian Carlstrombe977852011-07-19 14:54:54 -07003120// Create an array class (i.e. the class object for the array, not the
3121// array itself). "descriptor" looks like "[C" or "[[[[B" or
3122// "[Ljava/lang/String;".
3123//
3124// If "descriptor" refers to an array of primitives, look up the
3125// primitive type's internally-generated class object.
3126//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003127// "class_loader" is the class loader of the class that's referring to
3128// us. It's used to ensure that we're looking for the element type in
3129// the right context. It does NOT become the class loader for the
3130// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003131//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003132// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003133mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003134 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003135 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003136 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003137 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003138 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3139 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003140 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003141 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003142 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003143 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3144 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003145 if (component_type.Get() == nullptr) {
3146 DCHECK(self->IsExceptionPending());
3147 return nullptr;
3148 } else {
3149 self->ClearException();
3150 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003151 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003152 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3153 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3154 return nullptr;
3155 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003156 // See if the component type is already loaded. Array classes are
3157 // always associated with the class loader of their underlying
3158 // element type -- an array of Strings goes with the loader for
3159 // java/lang/String -- so we need to look for it there. (The
3160 // caller should have checked for the existence of the class
3161 // before calling here, but they did so with *their* class loader,
3162 // not the component type's loader.)
3163 //
3164 // If we find it, the caller adds "loader" to the class' initiating
3165 // loader list, which should prevent us from going through this again.
3166 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003167 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003168 // are the same, because our caller (FindClass) just did the
3169 // lookup. (Even if we get this wrong we still have correct behavior,
3170 // because we effectively do this lookup again when we add the new
3171 // class to the hash table --- necessary because of possible races with
3172 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003173 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003174 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003175 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003176 return new_class;
3177 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003178 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003179
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003180 // Fill out the fields in the Class.
3181 //
3182 // It is possible to execute some methods against arrays, because
3183 // all arrays are subclasses of java_lang_Object_, so we need to set
3184 // up a vtable. We can just point at the one in java_lang_Object_.
3185 //
3186 // Array classes are simple enough that we don't need to do a full
3187 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003188 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003189 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003190 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003191 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003192 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003193 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003194 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003195 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003196 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003197 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003198 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003199 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003200 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003201 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003202 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003203 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003204 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003205 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003206 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003207 }
3208 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003209 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003210 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003211 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003212 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003213 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003214 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003215 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003216 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003217 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003218 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003219 new_class->SetSuperClass(java_lang_Object);
3220 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003221 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003222 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003223 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003224 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003225 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3226 Runtime::Current()->GetImtUnimplementedMethod());
3227 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003228 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003229 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003230 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003231 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003232
3233
3234 // All arrays have java/lang/Cloneable and java/io/Serializable as
3235 // interfaces. We need to set that up here, so that stuff like
3236 // "instanceof" works right.
3237 //
3238 // Note: The GC could run during the call to FindSystemClass,
3239 // so we need to make sure the class object is GC-valid while we're in
3240 // there. Do this by clearing the interface list so the GC will just
3241 // think that the entries are null.
3242
3243
3244 // Use the single, global copies of "interfaces" and "iftable"
3245 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003246 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003247 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003248 CHECK(array_iftable != nullptr);
3249 new_class->SetIfTable(array_iftable);
3250 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003251
Elliott Hughes00626c22013-06-14 15:04:14 -07003252 // Inherit access flags from the component type.
3253 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3254 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3255 access_flags &= kAccJavaFlagsMask;
3256 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003257 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003258 access_flags |= kAccAbstract | kAccFinal;
3259 access_flags &= ~kAccInterface;
3260
3261 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003262
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003263 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003264 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003265 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003266 }
3267 // Another thread must have loaded the class after we
3268 // started but before we finished. Abandon what we've
3269 // done.
3270 //
3271 // (Yes, this happens.)
3272
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003273 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003274}
3275
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003276mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003277 switch (type) {
3278 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003279 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003280 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003281 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003282 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003283 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003284 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003285 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003286 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003287 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003288 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003289 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003290 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003291 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003292 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003293 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003294 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003295 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003296 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003297 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003298 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003299 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003300 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003301 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003302}
3303
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003304mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3305 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003306 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003307 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003308 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003309 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003310 source += " from ";
3311 source += dex_cache->GetLocation()->ToModifiedUtf8();
3312 }
3313 LOG(INFO) << "Loaded class " << descriptor << source;
3314 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003315 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003316 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003317 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003318 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003319 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003320 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003321 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003322 // Check a class loaded with the system class loader matches one in the image if the class
3323 // is in the image.
3324 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003325 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003326 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003327 }
3328 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003329 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003330 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003331 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003332 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003333 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003334 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003335}
3336
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003337mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3338 size_t hash) {
3339 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003340 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3341 hash);
3342 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003343 CHECK(klass->IsProxyClass());
3344 return nullptr;
3345 }
3346
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003347 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003348 CHECK_NE(existing, klass) << descriptor;
3349 CHECK(!existing->IsResolved()) << descriptor;
3350 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3351
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003352 CHECK(!klass->IsTemp()) << descriptor;
3353 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3354 dex_cache_image_class_lookup_required_) {
3355 // Check a class loaded with the system class loader matches one in the image if the class
3356 // is in the image.
3357 existing = LookupClassFromImage(descriptor);
3358 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003359 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003360 }
3361 }
3362 VerifyObject(klass);
3363
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003364 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003365 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003366 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003367 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003368 }
3369
3370 return existing;
3371}
3372
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003373bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003374 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003375 auto pair = std::make_pair(descriptor, class_loader);
3376 auto it = class_table_.Find(pair);
3377 if (it != class_table_.end()) {
3378 class_table_.Erase(it);
3379 return true;
3380 }
3381 it = pre_zygote_class_table_.Find(pair);
3382 if (it != pre_zygote_class_table_.end()) {
3383 pre_zygote_class_table_.Erase(it);
3384 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003385 }
3386 return false;
3387}
3388
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003389mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003390 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003391 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003392 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003393 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003394 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003395 return result;
3396 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003397 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003398 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3399 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003400 } else {
3401 // Lookup failed but need to search dex_caches_.
3402 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003403 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003404 InsertClass(descriptor, result, hash);
3405 } else {
3406 // Searching the image dex files/caches failed, we don't want to get into this situation
3407 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3408 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003409 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003410 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3411 MoveImageClassesToClassTable();
3412 }
3413 }
3414 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003415 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003416}
3417
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003418mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003419 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003420 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003421 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3422 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3423 if (it == pre_zygote_class_table_.end()) {
3424 it = class_table_.FindWithHash(descriptor_pair, hash);
3425 if (it == class_table_.end()) {
3426 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003427 }
3428 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003429 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003430}
3431
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003432static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3433 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3434 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003435 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003436 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3437 return root->AsObjectArray<mirror::DexCache>();
3438}
3439
3440void ClassLinker::MoveImageClassesToClassTable() {
3441 Thread* self = Thread::Current();
3442 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3443 if (!dex_cache_image_class_lookup_required_) {
3444 return; // All dex cache classes are already in the class table.
3445 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003446 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003447 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003448 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003449 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3450 mirror::DexCache* dex_cache = dex_caches->Get(i);
3451 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3452 for (int32_t j = 0; j < types->GetLength(); j++) {
3453 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003454 if (klass != nullptr) {
3455 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003456 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003457 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003458 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3459 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003460 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003461 << PrettyClassAndClassLoader(klass);
3462 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003463 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003464 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003465 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003466 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003467 }
3468 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003469 }
3470 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003471 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003472}
3473
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003474void ClassLinker::MoveClassTableToPreZygote() {
3475 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3476 DCHECK(pre_zygote_class_table_.Empty());
3477 pre_zygote_class_table_ = std::move(class_table_);
3478 class_table_.Clear();
3479}
3480
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003481mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003482 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003483 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3484 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3485 mirror::DexCache* dex_cache = dex_caches->Get(i);
3486 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003487 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003488 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003489 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003490 const DexFile::TypeId* type_id =
3491 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003492 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003493 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3494 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003495 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003496 return klass;
3497 }
3498 }
3499 }
3500 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003501 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003502}
3503
3504void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3505 result.clear();
3506 if (dex_cache_image_class_lookup_required_) {
3507 MoveImageClassesToClassTable();
3508 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003509 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3510 while (true) {
3511 auto it = class_table_.Find(descriptor);
3512 if (it == class_table_.end()) {
3513 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003514 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003515 result.push_back(it->Read());
3516 class_table_.Erase(it);
3517 }
3518 for (mirror::Class* k : result) {
3519 class_table_.Insert(GcRoot<mirror::Class>(k));
3520 }
3521 size_t pre_zygote_start = result.size();
3522 // Now handle the pre zygote table.
3523 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3524 // called from the debugger.
3525 while (true) {
3526 auto it = pre_zygote_class_table_.Find(descriptor);
3527 if (it == pre_zygote_class_table_.end()) {
3528 break;
3529 }
3530 result.push_back(it->Read());
3531 pre_zygote_class_table_.Erase(it);
3532 }
3533 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3534 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003535 }
3536}
3537
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003538void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003539 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003540 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003541
Ian Rogers9ffb0392012-09-10 11:56:50 -07003542 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003543 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003544 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003545 return;
3546 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003547 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3548 return;
3549 }
jeffhao98eacac2011-09-14 16:11:53 -07003550
Ian Rogers9ffb0392012-09-10 11:56:50 -07003551 // The class might already be erroneous, for example at compile time if we attempted to verify
3552 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003553 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003554 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003555 return;
3556 }
3557
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003558 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003559 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003560 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003561 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003562 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003563 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003564 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003565 }
jeffhao98eacac2011-09-14 16:11:53 -07003566
Jeff Hao4a200f52014-04-01 14:58:49 -07003567 // Skip verification if disabled.
3568 if (!Runtime::Current()->IsVerificationEnabled()) {
3569 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003570 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003571 return;
3572 }
3573
Ian Rogers9ffb0392012-09-10 11:56:50 -07003574 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003575 StackHandleScope<2> hs(self);
3576 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003577 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003578 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003579 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003580
3581 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003582 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003583 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003584 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003585 std::string error_msg(
3586 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3587 PrettyDescriptor(klass.Get()).c_str(),
3588 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003589 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003590 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3591 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003592 self->ClearException();
3593 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003594 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3595 if (cause.Get() != nullptr) {
3596 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003597 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003598 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003599 if (Runtime::Current()->IsCompiler()) {
3600 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3601 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003602 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003603 return;
3604 }
3605 }
3606
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003607 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003608 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003609 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003610 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003611 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003612 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003613 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003614 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003615 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3616 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003617 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003618 return;
3619 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003620 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003621 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003622 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003623 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003624 Runtime::Current()->IsCompiler(),
3625 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003626 }
3627 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003628 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003629 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003630 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3631 << " because: " << error_msg;
3632 }
Ian Rogers1f539342012-10-03 21:09:42 -07003633 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003634 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003635 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003636 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003637 // Even though there were no verifier failures we need to respect whether the super-class
3638 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003639 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003640 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003641 } else {
3642 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003643 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003644 // Pretend a soft failure occured so that we don't consider the class verified below.
3645 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003646 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003647 } else {
3648 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3649 // Soft failures at compile time should be retried at runtime. Soft
3650 // failures at runtime will be handled by slow paths in the generated
3651 // code. Set status accordingly.
3652 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003653 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003654 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003655 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003656 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3657 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003658 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003659 }
3660 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003661 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003662 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003663 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3664 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003665 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003666 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003667 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003668 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003669 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003670 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003671 // Let the interpreter know it by setting the kAccPreverified flag onto each
3672 // method.
3673 // Note: we're going here during compilation and at runtime. When we set the
3674 // kAccPreverified flag when compiling image classes, the flag is recorded
3675 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003676 EnsurePreverifiedMethods(klass);
3677 }
3678}
3679
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003680void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003681 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003682 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003683 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003684 }
jeffhao98eacac2011-09-14 16:11:53 -07003685}
3686
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003687bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3688 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003689 // If we're compiling, we can only verify the class using the oat file if
3690 // we are not compiling the image or if the class we're verifying is not part of
3691 // the app. In other words, we will only check for preverification of bootclasspath
3692 // classes.
3693 if (Runtime::Current()->IsCompiler()) {
3694 // Are we compiling the bootclasspath?
3695 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3696 return false;
3697 }
3698 // We are compiling an app (not the image).
3699
3700 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003701 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003702 return false;
3703 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003704 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003705
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003706 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003707 // In case we run without an image there won't be a backing oat file.
3708 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003709 return false;
3710 }
3711
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003712 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003713 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003714 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3715 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003716 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003717 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003718 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003719 // Compile time verification failed with a soft error. Compile time verification can fail
3720 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003721 // class ... {
3722 // Foo x;
3723 // .... () {
3724 // if (...) {
3725 // v1 gets assigned a type of resolved class Foo
3726 // } else {
3727 // v1 gets assigned a type of unresolved class Bar
3728 // }
3729 // iput x = v1
3730 // } }
3731 // when we merge v1 following the if-the-else it results in Conflict
3732 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3733 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3734 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3735 // at compile time).
3736 return false;
3737 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003738 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003739 // Compile time verification failed with a hard error. This is caused by invalid instructions
3740 // in the class. These errors are unrecoverable.
3741 return false;
3742 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003743 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003744 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3745 // not loading the class.
3746 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3747 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003748 return false;
3749 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003750 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003751 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003752 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003753 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003754 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003755}
3756
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003757void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003758 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003759 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3760 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3761 }
3762 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3763 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3764 }
3765}
3766
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003767void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003768 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003769 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3770 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003771 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003772 return; // native or abstract method
3773 }
3774 if (code_item->tries_size_ == 0) {
3775 return; // nothing to process
3776 }
Ian Rogers13735952014-10-08 12:43:28 -07003777 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003778 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3779 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3780 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3781 CatchHandlerIterator iterator(handlers_ptr);
3782 for (; iterator.HasNext(); iterator.Next()) {
3783 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3784 // unresolved exception types will be ignored by exception delivery
3785 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003786 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003787 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003788 DCHECK(Thread::Current()->IsExceptionPending());
3789 Thread::Current()->ClearException();
3790 }
3791 }
3792 }
3793 handlers_ptr = iterator.EndDataPointer();
3794 }
3795}
3796
Brian Carlstromea46f952013-07-30 01:26:50 -07003797static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003798static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3799 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003800
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003801mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003802 jobjectArray interfaces, jobject loader,
3803 jobjectArray methods, jobjectArray throws) {
3804 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003805 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003806 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003807 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003808 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003809 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003810 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003811 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003812 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003813 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003814 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3815 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003816 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003817 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003818 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003819 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003820 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003821 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003822
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003823 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003824 {
3825 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003826 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003827 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003828 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003829 }
3830 klass->SetSFields(sfields);
3831 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003832 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3833 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003834 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3835 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003836 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003837 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003838 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003839 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003840 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003841 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003842 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3843 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003844 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3845 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003846 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003847 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003848 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003849 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003850 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003851 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003852 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003853
Ian Rogers466bb252011-10-14 03:29:56 -07003854 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003855 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003856 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003857 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003858 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003859 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003860 }
3861 klass->SetDirectMethods(directs);
3862 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003863 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003864 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003865 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003866 }
3867 klass->SetDirectMethod(0, constructor);
3868 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003869
Mathieu Chartier590fee92013-09-13 13:46:47 -07003870 // Create virtual method using specified prototypes.
3871 size_t num_virtual_methods =
3872 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003873 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003874 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3875 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003876 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003877 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003878 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003879 }
3880 klass->SetVirtualMethods(virtuals);
3881 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003882 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003883 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003884 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3885 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003886 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003887 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003888 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003889 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003890 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003891 }
3892 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003893 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003894
3895 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003896 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003897 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003898
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003899 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3900 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003901 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003902 // Must hold lock on object when resolved.
3903 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003904 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003905 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003906 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003907 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003908 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003909 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003910 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003911 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003912
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003913 CHECK(klass->IsRetired());
3914 CHECK_NE(klass.Get(), new_class);
3915 klass.Assign(new_class);
3916
3917 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003918 interfaces_sfield->SetObject<false>(klass.Get(),
3919 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003920 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003921 throws_sfield->SetObject<false>(klass.Get(),
3922 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003923
3924 {
3925 // Lock on klass is released. Lock new class object.
3926 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003927 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003928 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003929
3930 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003931 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003932 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003933 CheckProxyConstructor(klass->GetDirectMethod(0));
3934 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003935 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003936 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3937 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003938 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3939 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003940 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003941 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003942
Mathieu Chartier590fee92013-09-13 13:46:47 -07003943 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003944 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003945 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003946 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3947
3948 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003949 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003950 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003951
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003952 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003953 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003954 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003955 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003956 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003957 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3958 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003959 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003960 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003961}
3962
Ian Rogersef7d42f2014-01-06 12:55:46 -08003963std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003964 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003965 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003966 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003967 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3968}
3969
Ian Rogersef7d42f2014-01-06 12:55:46 -08003970mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3971 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003972 DCHECK(proxy_class->IsProxyClass());
3973 DCHECK(proxy_method->IsProxyMethod());
3974 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003975 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003976 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003977 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003978 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003979 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003980 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003981 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003982 break;
3983 }
3984 }
3985 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003986 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003987 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003988 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003989 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003990 return resolved_method;
3991}
3992
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003993
Brian Carlstromea46f952013-07-30 01:26:50 -07003994mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003995 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003996 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003997 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003998 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003999 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07004000 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
4001 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02004002 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4003 // constructor method.
4004 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
4005 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07004006 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4007 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07004008 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
4009 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004010 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07004011 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004012 }
Ian Rogers466bb252011-10-14 03:29:56 -07004013 // Make this constructor public and fix the class to be our Proxy version
4014 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004015 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004016 return constructor;
4017}
4018
Brian Carlstromea46f952013-07-30 01:26:50 -07004019static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004020 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004021 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004022 CHECK_STREQ(constructor->GetName(), "<init>");
4023 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4024 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004025 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004026}
4027
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004028mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004029 Handle<mirror::Class> klass,
4030 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004031 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4032 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004033 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004034 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004035 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004036 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004037 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004038 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004039 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004040 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004041 }
Ian Rogers466bb252011-10-14 03:29:56 -07004042
4043 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4044 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004045 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004046 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004047
Ian Rogers466bb252011-10-14 03:29:56 -07004048 // At runtime the method looks like a reference and argument saving method, clone the code
4049 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004050 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4051 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004052 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004053
Ian Rogersc2b44472011-12-14 21:17:17 -08004054 return method;
4055}
Jesse Wilson95caa792011-10-12 18:14:17 -04004056
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004057static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4058 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004059 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004060 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004061 CHECK(!prototype->IsFinal());
4062 CHECK(method->IsFinal());
4063 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004064
4065 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4066 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07004067 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4068 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004069 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4070
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004071 CHECK_STREQ(method->GetName(), prototype->GetName());
4072 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004073 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004074 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004075}
4076
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004077static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4078 bool can_init_parents)
4079 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004080 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004081 return true;
4082 }
4083 if (!can_init_statics) {
4084 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004085 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004086 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004087 return false;
4088 }
4089 // Check if there are encoded static values needing initialization.
4090 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004091 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004092 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004093 if (dex_class_def->static_values_off_ != 0) {
4094 return false;
4095 }
4096 }
4097 }
4098 if (!klass->IsInterface() && klass->HasSuperClass()) {
4099 mirror::Class* super_class = klass->GetSuperClass();
4100 if (!can_init_parents && !super_class->IsInitialized()) {
4101 return false;
4102 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004103 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004104 return false;
4105 }
4106 }
4107 }
4108 return true;
4109}
4110
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004111bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004112 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004113 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4114
4115 // Are we already initialized and therefore done?
4116 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4117 // an initialized class will never change its state.
4118 if (klass->IsInitialized()) {
4119 return true;
4120 }
4121
4122 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004123 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004124 return false;
4125 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004126
Ian Rogers7b078e82014-09-10 14:44:24 -07004127 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004128 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004129 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004130 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004131
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004132 // Re-check under the lock in case another thread initialized ahead of us.
4133 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004134 return true;
4135 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004136
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004137 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004138 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004139 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004140 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004141 return false;
4142 }
4143
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004144 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004145
4146 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004147 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004148 if (!klass->IsVerified()) {
4149 // We failed to verify, expect either the klass to be erroneous or verification failed at
4150 // compile time.
4151 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004152 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004153 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004154 } else {
4155 CHECK(Runtime::Current()->IsCompiler());
4156 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004157 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004158 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004159 } else {
4160 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004161 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004162 }
4163
Brian Carlstromd1422f82011-09-28 11:37:09 -07004164 // If the class is kStatusInitializing, either this thread is
4165 // initializing higher up the stack or another thread has beat us
4166 // to initializing and we need to wait. Either way, this
4167 // invocation of InitializeClass will not be responsible for
4168 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004169 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004170 // Could have got an exception during verification.
4171 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004172 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004173 return false;
4174 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004175 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004176 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004177 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004178 return true;
4179 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004180 // No. That's fine. Wait for another thread to finish initializing.
4181 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004182 }
4183
4184 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004185 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004186 return false;
4187 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004188 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004189
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004190 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004191
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004192 // From here out other threads may observe that we're initializing and so changes of state
4193 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004194 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004195 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004196
4197 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004198 }
4199
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004200 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004201 if (!klass->IsInterface() && klass->HasSuperClass()) {
4202 mirror::Class* super_class = klass->GetSuperClass();
4203 if (!super_class->IsInitialized()) {
4204 CHECK(!super_class->IsInterface());
4205 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004206 StackHandleScope<1> hs(self);
4207 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004208 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004209 if (!super_initialized) {
4210 // The super class was verified ahead of entering initializing, we should only be here if
4211 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004212 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004213 << "Super class initialization failed for "
4214 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004215 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004216 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004217 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004218 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004219 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004220 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004221 return false;
4222 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004223 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004224 }
4225
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004226 const size_t num_static_fields = klass->NumStaticFields();
4227 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004228 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004229 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004230 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004231 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004232 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004233 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004234
4235 // Eagerly fill in static fields so that the we don't have to do as many expensive
4236 // Class::FindStaticField in ResolveField.
4237 for (size_t i = 0; i < num_static_fields; ++i) {
4238 mirror::ArtField* field = klass->GetStaticField(i);
4239 const uint32_t field_idx = field->GetDexFieldIndex();
4240 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4241 if (resolved_field == nullptr) {
4242 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004243 } else {
4244 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004245 }
4246 }
4247
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004248 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4249 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004250 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004251 ClassDataItemIterator field_it(dex_file, class_data);
4252 if (value_it.HasNext()) {
4253 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004254 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004255 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004256 StackHandleScope<1> hs2(self);
4257 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004258 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004259 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004260 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004261 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004262 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004263 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004264 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004265 }
4266 }
4267 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004268
Ian Rogersd91d6d62013-09-25 20:26:14 -07004269 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004270 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004271 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004272 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004273 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004274 }
4275
Ian Rogers7b078e82014-09-10 14:44:24 -07004276 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004277 uint64_t t1 = NanoTime();
4278
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004279 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004280 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004281 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004282
4283 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004284 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004285 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004286 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004287 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004288 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4289 RuntimeStats* thread_stats = self->GetStats();
4290 ++global_stats->class_init_count;
4291 ++thread_stats->class_init_count;
4292 global_stats->class_init_time_ns += (t1 - t0);
4293 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004294 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004295 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004296 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004297 std::string temp;
4298 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004299 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004300 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004301 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004302 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004303 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004304 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004305 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004306}
4307
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004308bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004309 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004310 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004311 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004312 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004313 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004314 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004315
4316 // When we wake up, repeat the test for init-in-progress. If
4317 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004318 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004319 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004320 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004321 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004322 return false;
4323 }
4324 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004325 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004326 continue;
4327 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004328 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004329 // Compile time initialization failed.
4330 return false;
4331 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004332 if (klass->IsErroneous()) {
4333 // The caller wants an exception, but it was thrown in a
4334 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004335 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004336 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004337 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004338 return false;
4339 }
4340 if (klass->IsInitialized()) {
4341 return true;
4342 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004343 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004344 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004345 }
Ian Rogers07140832014-09-30 15:43:59 -07004346 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004347}
4348
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004349bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004350 if (klass->IsInterface()) {
4351 return true;
4352 }
Ian Rogers151f2212014-05-06 11:27:27 -07004353 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004354 Thread* self = Thread::Current();
4355 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004356 MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4357 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004358 if (klass->HasSuperClass() &&
4359 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004360 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4361 mh.ChangeMethod(klass->GetVTableEntry(i));
4362 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004363 if (mh.GetMethod() != super_mh.GetMethod() &&
Ian Rogersded66a02014-10-28 18:12:55 -07004364 !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004365 ThrowLinkageError(klass.Get(),
4366 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004367 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004368 PrettyMethod(mh.GetMethod()).c_str(),
4369 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004370 return false;
4371 }
4372 }
4373 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004374 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004375 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4376 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4377 for (uint32_t j = 0; j < num_methods; ++j) {
4378 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4379 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004380 if (mh.GetMethod() != super_mh.GetMethod() &&
Ian Rogersded66a02014-10-28 18:12:55 -07004381 !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004382 ThrowLinkageError(klass.Get(),
4383 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004384 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004385 PrettyMethod(mh.GetMethod()).c_str(),
4386 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004387 return false;
4388 }
4389 }
4390 }
4391 }
4392 return true;
4393}
4394
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004395bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4396 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004397 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004398 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004399 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004400 return true;
4401 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004402 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004403 if (!success) {
4404 if (can_init_fields && can_init_parents) {
4405 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4406 }
4407 } else {
4408 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004409 }
4410 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004411}
4412
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004413void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4414 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4415 if (fields != nullptr) {
4416 for (int index = 0; index < fields->GetLength(); index ++) {
4417 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4418 fields->Get(index)->SetDeclaringClass(new_class);
4419 }
4420 }
4421 }
4422
4423 fields = new_class->GetSFields();
4424 if (fields != nullptr) {
4425 for (int index = 0; index < fields->GetLength(); index ++) {
4426 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4427 fields->Get(index)->SetDeclaringClass(new_class);
4428 }
4429 }
4430 }
4431
4432 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4433 if (methods != nullptr) {
4434 for (int index = 0; index < methods->GetLength(); index ++) {
4435 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4436 methods->Get(index)->SetDeclaringClass(new_class);
4437 }
4438 }
4439 }
4440
4441 methods = new_class->GetVirtualMethods();
4442 if (methods != nullptr) {
4443 for (int index = 0; index < methods->GetLength(); index ++) {
4444 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4445 methods->Get(index)->SetDeclaringClass(new_class);
4446 }
4447 }
4448 }
4449}
4450
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004451bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4452 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004453 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004454 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004455
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004456 if (!LinkSuperClass(klass)) {
4457 return false;
4458 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004459 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4460 self, Runtime::Current()->GetImtUnimplementedMethod());
4461 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004462 return false;
4463 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004464 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004465 return false;
4466 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004467 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004468 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004469 return false;
4470 }
4471 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004472 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004473
4474 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4475 // We don't need to retire this class as it has no embedded tables or it was created the
4476 // correct size during class linker initialization.
4477 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4478
4479 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004480 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004481 }
4482
4483 // This will notify waiters on klass that saw the not yet resolved
4484 // class in the class_table_ during EnsureResolved.
4485 klass->SetStatus(mirror::Class::kStatusResolved, self);
4486 *new_class = klass.Get();
4487 } else {
4488 CHECK(!klass->IsResolved());
4489 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004490 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004491 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004492 CHECK(self->IsExceptionPending()); // Expect an OOME.
4493 klass->SetStatus(mirror::Class::kStatusError, self);
4494 return false;
4495 }
4496
4497 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4498 StackHandleScope<1> hs(self);
4499 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4500 ObjectLock<mirror::Class> lock(self, new_class_h);
4501
4502 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4503
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004504 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4505 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004506 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004507
4508 // This will notify waiters on temp class that saw the not yet resolved class in the
4509 // class_table_ during EnsureResolved.
4510 klass->SetStatus(mirror::Class::kStatusRetired, self);
4511
4512 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4513 // This will notify waiters on new_class that saw the not yet resolved
4514 // class in the class_table_ during EnsureResolved.
4515 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004516 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004517 return true;
4518}
4519
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004520bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004521 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004522 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4523 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004524 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004525 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004526 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004527 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004528 return false;
4529 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004530 // Verify
4531 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004532 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004533 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004534 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004535 return false;
4536 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004537 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004538 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004539 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004540 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004541 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004542 for (size_t i = 0; i < interfaces->Size(); i++) {
4543 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004544 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004545 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004546 DCHECK(Thread::Current()->IsExceptionPending());
4547 return false;
4548 }
4549 // Verify
4550 if (!klass->CanAccess(interface)) {
4551 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004552 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004553 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004554 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004555 return false;
4556 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004557 }
4558 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004559 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004560 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004561 return true;
4562}
4563
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004564bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004565 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004566 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004567 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004568 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004569 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004570 return false;
4571 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004572 return true;
4573 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004574 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004575 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4576 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004577 return false;
4578 }
4579 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004580 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004581 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004582 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004583 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004584 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004585 return false;
4586 }
4587 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004588 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004589 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004590 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004591 return false;
4592 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004593
Brian Carlstromf3632832014-05-20 15:36:53 -07004594 // Inherit kAccClassIsFinalizable from the superclass in case this
4595 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004596 if (super->IsFinalizable()) {
4597 klass->SetFinalizable();
4598 }
4599
Elliott Hughes2da50362011-10-10 16:57:08 -07004600 // Inherit reference flags (if any) from the superclass.
4601 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4602 if (reference_flags != 0) {
4603 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4604 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004605 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004606 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004607 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004608 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004609 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004610 return false;
4611 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004612
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004613 if (kIsDebugBuild) {
4614 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004615 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004616 CHECK(super->IsResolved());
4617 super = super->GetSuperClass();
4618 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004619 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004620 return true;
4621}
4622
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004623// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004624bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004625 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4626 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004627 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004628 if (klass->IsInterface()) {
4629 // No vtable.
4630 size_t count = klass->NumVirtualMethods();
4631 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004632 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004633 return false;
4634 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004635 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004636 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004637 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004638 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4639 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004640 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004641 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004642}
4643
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004644// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4645// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4646// caches in the implementation below.
4647class MethodNameAndSignatureComparator FINAL : public ValueObject {
4648 public:
4649 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4650 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4651 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4652 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004653 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4654 }
4655
4656 const char* GetName() {
4657 if (name_ == nullptr) {
4658 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4659 }
4660 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004661 }
4662
4663 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4664 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4665 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4666 const DexFile* other_dex_file = other->GetDexFile();
4667 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4668 if (dex_file_ == other_dex_file) {
4669 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4670 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004671 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004672 uint32_t other_name_len;
4673 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4674 &other_name_len);
4675 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4676 return false;
4677 }
4678 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4679 }
4680
4681 private:
4682 // Dex file for the method to compare against.
4683 const DexFile* const dex_file_;
4684 // MethodId for the method to compare against.
4685 const DexFile::MethodId* const mid_;
4686 // Lazily computed name from the dex file's strings.
4687 const char* name_;
4688 // Lazily computed name length.
4689 uint32_t name_len_;
4690};
4691
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004692class LinkVirtualHashTable {
4693 public:
4694 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4695 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4696 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4697 }
4698 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4699 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4700 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004701 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004702 uint32_t index = hash % hash_size_;
4703 // Linear probe until we have an empty slot.
4704 while (hash_table_[index] != invalid_index_) {
4705 if (++index == hash_size_) {
4706 index = 0;
4707 }
4708 }
4709 hash_table_[index] = virtual_method_index;
4710 }
4711 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4712 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4713 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004714 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004715 size_t index = hash % hash_size_;
4716 while (true) {
4717 const uint32_t value = hash_table_[index];
4718 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4719 // the block and can safely assume not found.
4720 if (value == invalid_index_) {
4721 break;
4722 }
4723 if (value != removed_index_) { // This signifies not already overriden.
4724 mirror::ArtMethod* virtual_method =
4725 klass_->GetVirtualMethodDuringLinking(value);
4726 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4727 hash_table_[index] = removed_index_;
4728 return value;
4729 }
4730 }
4731 if (++index == hash_size_) {
4732 index = 0;
4733 }
4734 }
4735 return GetNotFoundIndex();
4736 }
4737 static uint32_t GetNotFoundIndex() {
4738 return invalid_index_;
4739 }
4740
4741 private:
4742 static const uint32_t invalid_index_;
4743 static const uint32_t removed_index_;
4744
4745 Handle<mirror::Class> klass_;
4746 const size_t hash_size_;
4747 uint32_t* const hash_table_;
4748};
4749
4750const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4751const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4752
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004753bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004754 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004755 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004756 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4757 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004758 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004759 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004760 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004761 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4762 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4763 if (UNLIKELY(vtable.Get() == nullptr)) {
4764 CHECK(self->IsExceptionPending()); // OOME.
4765 return false;
4766 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004767 for (size_t i = 0; i < super_vtable_length; i++) {
4768 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004769 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004770 if (num_virtual_methods == 0) {
4771 klass->SetVTable(vtable.Get());
4772 return true;
4773 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004774 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004775 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4776 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4777 if (num_virtual_methods == 0) {
4778 klass->SetVTable(super_vtable);
4779 return true;
4780 }
4781 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004782 if (UNLIKELY(vtable.Get() == nullptr)) {
4783 CHECK(self->IsExceptionPending()); // OOME.
4784 return false;
4785 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004786 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004787 // How the algorithm works:
4788 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4789 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4790 // method which has not been matched to a vtable method, and j if the virtual method at the
4791 // index overrode the super virtual method at index j.
4792 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4793 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4794 // the need for the initial vtable which we later shrink back down).
4795 // 3. Add non overridden methods to the end of the vtable.
4796 static constexpr size_t kMaxStackHash = 250;
4797 const size_t hash_table_size = num_virtual_methods * 3;
4798 uint32_t* hash_table_ptr;
4799 std::unique_ptr<uint32_t[]> hash_heap_storage;
4800 if (hash_table_size <= kMaxStackHash) {
4801 hash_table_ptr = reinterpret_cast<uint32_t*>(
4802 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4803 } else {
4804 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4805 hash_table_ptr = hash_heap_storage.get();
4806 }
4807 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4808 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004809 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004810 hash_table.Add(i);
4811 }
4812 // Loop through each super vtable method and see if they are overriden by a method we added to
4813 // the hash table.
4814 for (size_t j = 0; j < super_vtable_length; ++j) {
4815 // Search the hash table to see if we are overidden by any method.
4816 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4817 MethodNameAndSignatureComparator super_method_name_comparator(
4818 super_method->GetInterfaceMethodIfProxy());
4819 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4820 if (hash_index != hash_table.GetNotFoundIndex()) {
4821 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4822 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4823 super_method->GetAccessFlags())) {
4824 if (super_method->IsFinal()) {
4825 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4826 PrettyMethod(virtual_method).c_str(),
4827 super_method->GetDeclaringClassDescriptor());
4828 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004829 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004830 vtable->SetWithoutChecks<false>(j, virtual_method);
4831 virtual_method->SetMethodIndex(j);
4832 } else {
4833 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004834 << " would have incorrectly overridden the package-private method in "
4835 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004836 }
4837 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004838 }
4839 // Add the non overridden methods at the end.
4840 size_t actual_count = super_vtable_length;
4841 for (size_t i = 0; i < num_virtual_methods; ++i) {
4842 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4843 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4844 if (method_idx < super_vtable_length &&
4845 local_method == vtable->GetWithoutChecks(method_idx)) {
4846 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004847 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004848 vtable->SetWithoutChecks<false>(actual_count, local_method);
4849 local_method->SetMethodIndex(actual_count);
4850 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004851 }
4852 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004853 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004854 return false;
4855 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004856 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004857 CHECK_LE(actual_count, max_count);
4858 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004859 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004860 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004861 CHECK(self->IsExceptionPending()); // OOME.
4862 return false;
4863 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004864 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004865 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004866 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004867 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004868 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004869 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4870 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004871 return false;
4872 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004873 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4874 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004875 CHECK(self->IsExceptionPending()); // OOME.
4876 return false;
4877 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004878 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004879 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004880 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004881 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004882 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004883 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004884 }
4885 return true;
4886}
4887
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004888bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4889 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4890 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004891 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004892 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004893 const bool has_superclass = klass->HasSuperClass();
4894 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4895 const bool have_interfaces = interfaces.Get() != nullptr;
4896 const size_t num_interfaces =
4897 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4898 if (num_interfaces == 0) {
4899 if (super_ifcount == 0) {
4900 // Class implements no interfaces.
4901 DCHECK_EQ(klass->GetIfTableCount(), 0);
4902 DCHECK(klass->GetIfTable() == nullptr);
4903 return true;
4904 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004905 // Class implements same interfaces as parent, are any of these not marker interfaces?
4906 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004907 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004908 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004909 if (super_iftable->GetMethodArrayCount(i) > 0) {
4910 has_non_marker_interface = true;
4911 break;
4912 }
4913 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004914 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004915 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004916 klass->SetIfTable(super_iftable);
4917 return true;
4918 }
4919 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004920 size_t ifcount = super_ifcount + num_interfaces;
4921 for (size_t i = 0; i < num_interfaces; i++) {
4922 mirror::Class* interface = have_interfaces ?
4923 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4924 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004925 if (UNLIKELY(!interface->IsInterface())) {
4926 std::string temp;
4927 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4928 PrettyDescriptor(klass.Get()).c_str(),
4929 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4930 return false;
4931 }
4932 ifcount += interface->GetIfTableCount();
4933 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004934 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004935 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004936 CHECK(self->IsExceptionPending()); // OOME.
4937 return false;
4938 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004939 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004940 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004941 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004942 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004943 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004944 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004945 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004946 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004947 // Flatten the interface inheritance hierarchy.
4948 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004949 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004950 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4951 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004952 // Check if interface is already in iftable
4953 bool duplicate = false;
4954 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004955 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004956 if (existing_interface == interface) {
4957 duplicate = true;
4958 break;
4959 }
4960 }
4961 if (!duplicate) {
4962 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004963 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004964 // Add this interface's non-duplicate super-interfaces.
4965 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004966 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004967 bool super_duplicate = false;
4968 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004969 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004970 if (existing_interface == super_interface) {
4971 super_duplicate = true;
4972 break;
4973 }
4974 }
4975 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004976 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004977 }
4978 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004979 }
4980 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004981 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004982 // Shrink iftable in case duplicates were found
4983 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004984 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004985 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004986 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004987 CHECK(self->IsExceptionPending()); // OOME.
4988 return false;
4989 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004990 ifcount = idx;
4991 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004992 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004993 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004994 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004995 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004996 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004997 return true;
4998 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004999 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005000 size_t max_miranda_methods = 0; // The max size of miranda_list.
5001 for (size_t i = 0; i < ifcount; ++i) {
5002 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
5003 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005004 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005005 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005006 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5007 hs.NewHandle(klass->GetVTableDuringLinking()));
5008 // Copy the IMT from the super class if possible.
5009 bool extend_super_iftable = false;
5010 if (has_superclass) {
5011 mirror::Class* super_class = klass->GetSuperClass();
5012 extend_super_iftable = true;
5013 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5014 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5015 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5016 }
5017 } else {
5018 // No imt in the super class, need to reconstruct from the iftable.
5019 mirror::IfTable* if_table = super_class->GetIfTable();
5020 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5021 const size_t length = super_class->GetIfTableCount();
5022 for (size_t i = 0; i < length; ++i) {
5023 mirror::Class* interface = iftable->GetInterface(i);
5024 const size_t num_virtuals = interface->NumVirtualMethods();
5025 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5026 DCHECK_EQ(num_virtuals, method_array_count);
5027 if (method_array_count == 0) {
5028 continue;
5029 }
5030 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5031 for (size_t j = 0; j < num_virtuals; ++j) {
5032 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5033 if (method->IsMiranda()) {
5034 continue;
5035 }
5036 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5037 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5038 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5039 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5040 out_imt->SetReference(imt_index, method);
5041 } else if (imt_ref != conflict_method) {
5042 out_imt->SetReference(imt_index, conflict_method);
5043 }
5044 }
5045 }
5046 }
5047 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005048 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005049 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005050 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005051 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005052 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005053 const bool is_super = i < super_ifcount;
5054 const bool super_interface = is_super && extend_super_iftable;
5055 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5056 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5057 if (super_interface) {
5058 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5059 DCHECK(if_table != nullptr);
5060 DCHECK(if_table->GetMethodArray(i) != nullptr);
5061 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005062 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005063 AsObjectArray<mirror::ArtMethod>());
5064 // We are overwriting a super class interface, try to only virtual methods instead of the
5065 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005066 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005067 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005068 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005069 // A new interface, we need the whole vtable incase a new interface method is implemented
5070 // in the whole superclass.
5071 input_array = vtable;
5072 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005073 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005074 CHECK(self->IsExceptionPending()); // OOME.
5075 return false;
5076 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005077 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005078 if (input_array.Get() == nullptr) {
5079 // If the added virtual methods is empty, do nothing.
5080 DCHECK(super_interface);
5081 continue;
5082 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005083 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005084 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005085 MethodNameAndSignatureComparator interface_name_comparator(
5086 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005087 int32_t k;
5088 // For each method listed in the interface's method list, find the
5089 // matching method in our class's method list. We want to favor the
5090 // subclass over the superclass, which just requires walking
5091 // back from the end of the vtable. (This only matters if the
5092 // superclass defines a private method and this class redefines
5093 // it -- otherwise it would use the same vtable slot. In .dex files
5094 // those don't end up in the virtual method table, so it shouldn't
5095 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005096 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5097 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005098 mirror::ArtMethod* vtable_method_for_name_comparison =
5099 vtable_method->GetInterfaceMethodIfProxy();
5100 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005101 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005102 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005103 ThrowIllegalAccessError(
5104 klass.Get(),
5105 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005106 PrettyMethod(vtable_method).c_str(),
5107 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005108 return false;
5109 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005110 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005111 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005112 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5113 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5114 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5115 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5116 out_imt->SetReference(imt_index, vtable_method);
5117 } else if (imt_ref != conflict_method) {
5118 // If we are not a conflict and we have the same signature and name as the imt entry,
5119 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005120 MethodNameAndSignatureComparator imt_ref_name_comparator(
5121 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005122 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005123 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005124 out_imt->SetReference(imt_index, vtable_method);
5125 } else {
5126 out_imt->SetReference(imt_index, conflict_method);
5127 }
Jeff Hao88474b42013-10-23 16:24:40 -07005128 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005129 break;
5130 }
5131 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005132 if (k < 0 && !super_interface) {
5133 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005134 for (size_t l = 0; l < miranda_list_size; ++l) {
5135 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005136 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005137 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005138 break;
5139 }
5140 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005141 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005142 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005143 miranda_method = interface_method->Clone(self)->AsArtMethod();
5144 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005145 CHECK(self->IsExceptionPending()); // OOME.
5146 return false;
5147 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005148 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005149 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005150 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005151 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005152 }
5153 }
5154 }
5155 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005156 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005157 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005158 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005159 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5160 if (old_method_count == 0) {
5161 virtuals = AllocArtMethodArray(self, new_method_count);
5162 } else {
5163 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5164 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005165 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005166 CHECK(self->IsExceptionPending()); // OOME.
5167 return false;
5168 }
5169 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005170
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005171 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005172 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005173 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005174 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005175 CHECK(self->IsExceptionPending()); // OOME.
5176 return false;
5177 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005178 for (size_t i = 0; i < miranda_list_size; ++i) {
5179 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005180 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005181 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5182 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5183 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005184 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005185 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005186 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005187 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005188 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005189
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005190 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005191 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5192 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5193 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005194 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005195 }
5196
Ian Rogers7b078e82014-09-10 14:44:24 -07005197 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005198 return true;
5199}
5200
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005201bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005202 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005203 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005204}
5205
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005206bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005207 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005208 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005209}
5210
Brian Carlstromdbc05252011-09-09 01:59:59 -07005211struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005212 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5213 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005214 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005215 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005216 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005217 // 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 -07005218 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5219 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005220 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005221 if (type1 == Primitive::kPrimNot) {
5222 // Reference always goes first.
5223 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005224 }
Vladimir Markod5777482014-11-12 17:02:02 +00005225 if (type2 == Primitive::kPrimNot) {
5226 // Reference always goes first.
5227 return false;
5228 }
5229 size_t size1 = Primitive::ComponentSize(type1);
5230 size_t size2 = Primitive::ComponentSize(type2);
5231 if (size1 != size2) {
5232 // Larger primitive types go first.
5233 return size1 > size2;
5234 }
5235 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5236 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005237 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005238 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5239 // by name and for equal names by type id index.
5240 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5241 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005242 }
5243};
5244
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005245bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005246 size_t* class_size) {
5247 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005248 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005249 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005250
Brian Carlstromea46f952013-07-30 01:26:50 -07005251 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005252 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005253
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005254 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005255 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005256 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005257 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005258 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005259 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005260 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005261 CHECK(super_class->IsResolved())
5262 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005263 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005264 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005265 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005266
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005267 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005268
Brian Carlstromdbc05252011-09-09 01:59:59 -07005269 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005270 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005271 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005272 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005273 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005274 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005275 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005276 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005277 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005278 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005279 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5280 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005281
Fred Shih381e4ca2014-08-25 17:24:27 -07005282 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005283 size_t current_field = 0;
5284 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005285 FieldGaps gaps;
5286
Brian Carlstromdbc05252011-09-09 01:59:59 -07005287 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005288 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005289 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005290 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005291 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005292 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005293 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005294 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5295 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005296 MemberOffset old_offset = field_offset;
5297 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5298 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5299 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005300 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005301 grouped_and_sorted_fields.pop_front();
5302 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005303 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005304 field_offset = MemberOffset(field_offset.Uint32Value() +
5305 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005306 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005307 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5308 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005309 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5310 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5311 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5312 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005313 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5314 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005315 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005316
Elliott Hughesadb460d2011-10-05 17:02:34 -07005317 // 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 -07005318 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005319 // We know there are no non-reference fields in the Reference classes, and we know
5320 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005321 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005322 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005323 --num_reference_fields;
5324 }
5325
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005326 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005327 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005328 if (is_static) {
5329 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005330 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005331 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005332 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005333 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005334 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
5335 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
5336 } else {
5337 std::string temp;
5338 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5339 size_t previous_size = klass->GetObjectSize();
5340 if (previous_size != 0) {
5341 // Make sure that we didn't originally have an incorrect size.
5342 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5343 }
5344 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005345 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005346 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005347 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005348
5349 if (kIsDebugBuild) {
5350 // Make sure that the fields array is ordered by name but all reference
5351 // offsets are at the beginning as far as alignment allows.
5352 MemberOffset start_ref_offset = is_static
5353 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5354 : klass->GetFirstReferenceInstanceFieldOffset();
5355 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5356 num_reference_fields *
5357 sizeof(mirror::HeapReference<mirror::Object>));
5358 MemberOffset current_ref_offset = start_ref_offset;
5359 for (size_t i = 0; i < num_fields; i++) {
5360 mirror::ArtField* field = fields->Get(i);
5361 if ((false)) { // enable to debug field layout
5362 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5363 << " class=" << PrettyClass(klass.Get())
5364 << " field=" << PrettyField(field)
5365 << " offset="
5366 << field->GetField32(mirror::ArtField::OffsetOffset());
5367 }
5368 if (i != 0) {
5369 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005370 // NOTE: The field names can be the same. This is not possible in the Java language
5371 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5372 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005373 }
5374 Primitive::Type type = field->GetTypeAsPrimitiveType();
5375 bool is_primitive = type != Primitive::kPrimNot;
5376 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5377 strcmp("referent", field->GetName()) == 0) {
5378 is_primitive = true; // We lied above, so we have to expect a lie here.
5379 }
5380 MemberOffset offset = field->GetOffsetDuringLinking();
5381 if (is_primitive) {
5382 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5383 // Shuffled before references.
5384 size_t type_size = Primitive::ComponentSize(type);
5385 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5386 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5387 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5388 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5389 }
5390 } else {
5391 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5392 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5393 sizeof(mirror::HeapReference<mirror::Object>));
5394 }
5395 }
5396 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5397 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005398 return true;
5399}
5400
Vladimir Marko76649e82014-11-10 18:32:59 +00005401// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005402void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005403 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005404 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005405 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005406 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005407 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005408 // Compute reference offsets unless our superclass overflowed.
5409 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5410 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005411 if (num_reference_fields != 0u) {
5412 // All of the fields that contain object references are guaranteed be grouped in memory
5413 // starting at an appropriately aligned address after super class object data.
5414 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5415 sizeof(mirror::HeapReference<mirror::Object>));
5416 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005417 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005418 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005419 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005420 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005421 reference_offsets |= (0xffffffffu << start_bit) &
5422 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005423 }
5424 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005425 }
5426 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005427 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005428}
5429
Mathieu Chartier590fee92013-09-13 13:46:47 -07005430mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005431 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005432 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005433 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005434 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005435 return resolved;
5436 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005437 uint32_t utf16_length;
5438 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005439 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005440 dex_cache->SetResolvedString(string_idx, string);
5441 return string;
5442}
5443
Mathieu Chartier590fee92013-09-13 13:46:47 -07005444mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005445 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005446 StackHandleScope<2> hs(Thread::Current());
5447 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5448 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005449 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5450}
5451
5452mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005453 Handle<mirror::DexCache> dex_cache,
5454 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005455 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005456 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005457 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005458 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005459 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005460 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005461 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005462 // TODO: we used to throw here if resolved's class loader was not the
5463 // boot class loader. This was to permit different classes with the
5464 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005465 dex_cache->SetResolvedType(type_idx, resolved);
5466 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005467 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005468 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005469 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005470 StackHandleScope<1> hs(self);
5471 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005472 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005473 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005474 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005475 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005476 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005477 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005478 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005479 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005480 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005481 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005482 return resolved;
5483}
5484
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005485mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005486 Handle<mirror::DexCache> dex_cache,
5487 Handle<mirror::ClassLoader> class_loader,
5488 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005489 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005490 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005491 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005492 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005493 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005494 return resolved;
5495 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005496 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005497 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005498 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005499 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005500 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005501 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005502 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005503 // Scan using method_idx, this saves string compares but will only hit for matching dex
5504 // caches/files.
5505 switch (type) {
5506 case kDirect: // Fall-through.
5507 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005508 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005509 break;
5510 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005511 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005512 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005513 break;
5514 case kSuper: // Fall-through.
5515 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005516 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005517 break;
5518 default:
5519 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005520 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005521 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005522 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005523 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005524 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005525 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005526 switch (type) {
5527 case kDirect: // Fall-through.
5528 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005529 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005530 break;
5531 case kInterface:
5532 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005533 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005534 break;
5535 case kSuper: // Fall-through.
5536 case kVirtual:
5537 resolved = klass->FindVirtualMethod(name, signature);
5538 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005539 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005540 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005541 // If we found a method, check for incompatible class changes.
5542 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005543 // Be a good citizen and update the dex cache to speed subsequent calls.
5544 dex_cache->SetResolvedMethod(method_idx, resolved);
5545 return resolved;
5546 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005547 // If we had a method, it's an incompatible-class-change error.
5548 if (resolved != nullptr) {
5549 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5550 } else {
5551 // We failed to find the method which means either an access error, an incompatible class
5552 // change, or no such method. First try to find the method among direct and virtual methods.
5553 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5554 const Signature signature = dex_file.GetMethodSignature(method_id);
5555 switch (type) {
5556 case kDirect:
5557 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005558 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005559 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5560 // have had a resolved method before, which triggers the "true" branch above.
5561 break;
5562 case kInterface:
5563 case kVirtual:
5564 case kSuper:
5565 resolved = klass->FindDirectMethod(name, signature);
5566 break;
5567 }
5568
5569 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005570 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005571 if (resolved != nullptr && referrer.Get() != nullptr) {
5572 mirror::Class* methods_class = resolved->GetDeclaringClass();
5573 mirror::Class* referring_class = referrer->GetDeclaringClass();
5574 if (!referring_class->CanAccess(methods_class)) {
5575 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5576 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005577 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005578 } else if (!referring_class->CanAccessMember(methods_class,
5579 resolved->GetAccessFlags())) {
5580 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005581 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005582 }
5583 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005584 if (!exception_generated) {
5585 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5586 // interface methods and throw if we find the method there. If we find nothing, throw a
5587 // NoSuchMethodError.
5588 switch (type) {
5589 case kDirect:
5590 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005591 if (resolved != nullptr) {
5592 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5593 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005594 resolved = klass->FindInterfaceMethod(name, signature);
5595 if (resolved != nullptr) {
5596 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5597 } else {
5598 ThrowNoSuchMethodError(type, klass, name, signature);
5599 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005600 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005601 break;
5602 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005603 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005604 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5605 } else {
5606 resolved = klass->FindVirtualMethod(name, signature);
5607 if (resolved != nullptr) {
5608 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5609 } else {
5610 ThrowNoSuchMethodError(type, klass, name, signature);
5611 }
5612 }
5613 break;
5614 case kSuper:
5615 if (resolved != nullptr) {
5616 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005617 } else {
5618 ThrowNoSuchMethodError(type, klass, name, signature);
5619 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005620 break;
5621 case kVirtual:
5622 if (resolved != nullptr) {
5623 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5624 } else {
5625 resolved = klass->FindInterfaceMethod(name, signature);
5626 if (resolved != nullptr) {
5627 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5628 } else {
5629 ThrowNoSuchMethodError(type, klass, name, signature);
5630 }
5631 }
5632 break;
5633 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005634 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005635 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005636 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005637 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005638 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005639}
5640
Mathieu Chartier590fee92013-09-13 13:46:47 -07005641mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005642 Handle<mirror::DexCache> dex_cache,
5643 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005644 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005645 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005646 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005647 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005648 return resolved;
5649 }
5650 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005651 Thread* const self = Thread::Current();
5652 StackHandleScope<1> hs(self);
5653 Handle<mirror::Class> klass(
5654 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005655 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005656 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005657 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005658 }
5659
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005660 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005661 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005662 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005663 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005664 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005665
Andreas Gampe58a5af82014-07-31 16:23:49 -07005666 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005667 const char* name = dex_file.GetFieldName(field_id);
5668 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5669 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005670 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005671 } else {
5672 resolved = klass->FindInstanceField(name, type);
5673 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005674 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005675 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005676 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005677 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005678 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005679 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005680 return resolved;
5681}
5682
Brian Carlstromea46f952013-07-30 01:26:50 -07005683mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005684 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005685 Handle<mirror::DexCache> dex_cache,
5686 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005687 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005688 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005689 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005690 return resolved;
5691 }
5692 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005693 Thread* self = Thread::Current();
5694 StackHandleScope<1> hs(self);
5695 Handle<mirror::Class> klass(
5696 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005697 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005698 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005699 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005700 }
5701
Ian Rogersdfb325e2013-10-30 01:00:44 -07005702 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5703 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005704 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005705 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005706 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005707 dex_cache->SetResolvedField(field_idx, resolved);
5708 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005709 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005710 }
5711 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005712}
5713
Brian Carlstromea46f952013-07-30 01:26:50 -07005714const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005715 uint32_t* length) {
5716 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5717 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005718 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005719 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005720 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005721}
5722
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005723void ClassLinker::DumpAllClasses(int flags) {
5724 if (dex_cache_image_class_lookup_required_) {
5725 MoveImageClassesToClassTable();
5726 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005727 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5728 // 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 -08005729 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005730 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005731 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005732 for (GcRoot<mirror::Class>& it : class_table_) {
5733 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005734 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005735 }
5736
5737 for (size_t i = 0; i < all_classes.size(); ++i) {
5738 all_classes[i]->DumpClass(std::cerr, flags);
5739 }
5740}
5741
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005742static OatFile::OatMethod CreateOatMethod(const void* code, bool is_portable) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005743 CHECK_EQ(kUsePortableCompiler, is_portable);
5744 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005745 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5746 base -= sizeof(void*); // Move backward so that code_offset != 0.
5747 const uint32_t code_offset = sizeof(void*);
5748 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005749}
5750
5751bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5752 return (entry_point == GetPortableResolutionStub()) ||
5753 (portable_resolution_trampoline_ == entry_point);
5754}
5755
5756bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5757 return (entry_point == GetQuickResolutionStub()) ||
5758 (quick_resolution_trampoline_ == entry_point);
5759}
5760
5761bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5762 return (entry_point == GetPortableToInterpreterBridge());
5763 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5764}
5765
5766bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5767 return (entry_point == GetQuickToInterpreterBridge()) ||
5768 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5769}
5770
5771bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5772 return (entry_point == GetQuickGenericJniStub()) ||
5773 (quick_generic_jni_trampoline_ == entry_point);
5774}
5775
5776const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5777 return GetQuickGenericJniStub();
5778}
5779
5780void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5781 bool is_portable) const {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005782 OatFile::OatMethod oat_method = CreateOatMethod(method_code, is_portable);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005783 oat_method.LinkMethod(method);
5784 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5785 // Create bridges to transition between different kinds of compiled bridge.
5786 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5787 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5788 } else {
5789 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5790 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5791 method->SetIsPortableCompiled();
5792 }
5793}
5794
5795void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5796 if (!method->IsNative()) {
5797 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5798 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5799 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5800 } else {
5801 const void* quick_method_code = GetQuickGenericJniStub();
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005802 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, false);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005803 oat_method.LinkMethod(method);
5804 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5805 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5806 }
5807}
5808
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005809void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005810 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005811 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005812 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005813 MoveImageClassesToClassTable();
5814 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005815 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005816 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5817 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005818}
5819
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005820size_t ClassLinker::NumLoadedClasses() {
5821 if (dex_cache_image_class_lookup_required_) {
5822 MoveImageClassesToClassTable();
5823 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005824 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005825 // Only return non zygote classes since these are the ones which apps which care about.
5826 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005827}
5828
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005829pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005830 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005831}
5832
5833pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005834 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005835}
5836
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005837void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005838 DCHECK(!init_done_);
5839
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005840 DCHECK(klass != nullptr);
5841 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005842
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005843 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005844 DCHECK(class_roots != nullptr);
5845 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005846 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005847}
5848
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005849const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5850 static const char* class_roots_descriptors[] = {
5851 "Ljava/lang/Class;",
5852 "Ljava/lang/Object;",
5853 "[Ljava/lang/Class;",
5854 "[Ljava/lang/Object;",
5855 "Ljava/lang/String;",
5856 "Ljava/lang/DexCache;",
5857 "Ljava/lang/ref/Reference;",
5858 "Ljava/lang/reflect/ArtField;",
5859 "Ljava/lang/reflect/ArtMethod;",
5860 "Ljava/lang/reflect/Proxy;",
5861 "[Ljava/lang/String;",
5862 "[Ljava/lang/reflect/ArtField;",
5863 "[Ljava/lang/reflect/ArtMethod;",
5864 "Ljava/lang/ClassLoader;",
5865 "Ljava/lang/Throwable;",
5866 "Ljava/lang/ClassNotFoundException;",
5867 "Ljava/lang/StackTraceElement;",
5868 "Z",
5869 "B",
5870 "C",
5871 "D",
5872 "F",
5873 "I",
5874 "J",
5875 "S",
5876 "V",
5877 "[Z",
5878 "[B",
5879 "[C",
5880 "[D",
5881 "[F",
5882 "[I",
5883 "[J",
5884 "[S",
5885 "[Ljava/lang/StackTraceElement;",
5886 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005887 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5888 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005889
5890 const char* descriptor = class_roots_descriptors[class_root];
5891 CHECK(descriptor != nullptr);
5892 return descriptor;
5893}
5894
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005895std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5896 const {
5897 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005898 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005899}
5900
5901bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5902 const GcRoot<mirror::Class>& b) {
5903 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5904 return false;
5905 }
5906 std::string temp;
5907 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5908}
5909
5910std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5911 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005912 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005913}
5914
5915bool ClassLinker::ClassDescriptorHashEquals::operator()(
5916 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5917 if (a.Read()->GetClassLoader() != b.second) {
5918 return false;
5919 }
5920 return a.Read()->DescriptorEquals(b.first);
5921}
5922
5923bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5924 const char* descriptor) {
5925 return a.Read()->DescriptorEquals(descriptor);
5926}
5927
5928std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005929 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005930}
5931
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005932} // namespace art