blob: 5718e44f9ced79523cbad834ff2bdbe516595243 [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 Rogers700a4022014-05-19 16:49:03 -070020#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070021#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070022#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070023#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070024#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080027#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010028#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080030#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000032#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080033#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "dex_file-inl.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070035#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070036#include "gc/accounting/card_table-inl.h"
37#include "gc/accounting/heap_bitmap.h"
38#include "gc/heap.h"
39#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070040#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070041#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070042#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070043#include "leb128.h"
Ian Rogers1ff3c982014-08-12 02:30:58 -070044#include "method_helper-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080045#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070046#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070047#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070048#include "mirror/art_field-inl.h"
49#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "mirror/class.h"
51#include "mirror/class-inl.h"
52#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070053#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
57#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070058#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070060#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080061#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070062#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070063#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070064#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070065#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070066#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070067#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070068#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080069#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070070#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070071
72namespace art {
73
Ian Rogers00f7d0e2012-07-19 15:28:27 -070074static void ThrowNoClassDefFoundError(const char* fmt, ...)
75 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070076 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070077static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070078 va_list args;
79 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080080 Thread* self = Thread::Current();
81 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
82 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080083 va_end(args);
84}
85
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080086static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070087 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070088 // The class failed to initialize on a previous attempt, so we want to throw
89 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
90 // failed in verification, in which case v2 5.4.1 says we need to re-throw
91 // the previous error.
Ian Rogers7b078e82014-09-10 14:44:24 -070092 Runtime* runtime = Runtime::Current();
93 bool is_compiler = runtime->IsCompiler();
94 if (!is_compiler) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070095 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
96 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070097
Elliott Hughes5c599942012-06-13 16:45:05 -070098 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -080099 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700100 if (is_compiler) {
101 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
102 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
103 self->SetException(ThrowLocation(), pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700104 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700105 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
106 if (c->GetVerifyErrorClass() != NULL) {
107 // TODO: change the verifier to store an _instance_, with a useful detail message?
108 std::string temp;
109 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
110 PrettyDescriptor(c).c_str());
111 } else {
112 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
113 PrettyDescriptor(c).c_str());
114 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700115 }
116}
117
Brian Carlstromb23eab12014-10-08 17:55:21 -0700118static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
119 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
120 if (VLOG_IS_ON(class_linker)) {
121 std::string temp;
122 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
123 << klass->GetLocation() << "\n" << Thread::Current()->GetException(nullptr)->Dump();
124 }
125}
126
127static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
128 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700129 Thread* self = Thread::Current();
130 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700131
132 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700133 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700134
135 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700136 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
137 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700138
Elliott Hughesa4f94742012-05-29 16:28:38 -0700139 // We only wrap non-Error exceptions; an Error can just be used as-is.
140 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800141 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700142 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
143 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700144 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700145 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700146}
147
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800148static size_t Hash(const char* s) {
149 // This is the java.lang.String hashcode for convenience, not interoperability.
150 size_t hash = 0;
151 for (; *s != '\0'; ++s) {
152 hash = hash * 31 + *s;
153 }
154 return hash;
155}
156
Fred Shih381e4ca2014-08-25 17:24:27 -0700157// Gap between two fields in object layout.
158struct FieldGap {
159 uint32_t start_offset; // The offset from the start of the object.
160 uint32_t size; // The gap size of 1, 2, or 4 bytes.
161};
162struct FieldGapsComparator {
163 explicit FieldGapsComparator() {
164 }
165 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
166 NO_THREAD_SAFETY_ANALYSIS {
167 // Sort by gap size, largest first.
168 return lhs.size > rhs.size;
169 }
170};
171typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
172
173// Adds largest aligned gaps to queue of gaps.
174void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
175 DCHECK(gaps != nullptr);
176
177 uint32_t current_offset = gap_start;
178 while (current_offset != gap_end) {
179 size_t remaining = gap_end - current_offset;
180 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
181 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
182 current_offset += sizeof(uint32_t);
183 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
184 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
185 current_offset += sizeof(uint16_t);
186 } else {
187 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
188 current_offset += sizeof(uint8_t);
189 }
190 DCHECK_LE(current_offset, gap_end) << "Overran gap";
191 }
192}
193// Shuffle fields forward, making use of gaps whenever possible.
194template<int n>
195static void ShuffleForward(const size_t num_fields, size_t* current_field_idx,
196 MemberOffset* field_offset,
197 mirror::ObjectArray<mirror::ArtField>* fields,
198 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
199 FieldGaps* gaps)
200 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
201 DCHECK(current_field_idx != nullptr);
202 DCHECK(grouped_and_sorted_fields != nullptr);
203 DCHECK(fields != nullptr || (num_fields == 0 && grouped_and_sorted_fields->empty()));
204 DCHECK(gaps != nullptr);
205 DCHECK(field_offset != nullptr);
206
207 DCHECK(IsPowerOfTwo(n));
208 while (!grouped_and_sorted_fields->empty()) {
209 mirror::ArtField* field = grouped_and_sorted_fields->front();
210 Primitive::Type type = field->GetTypeAsPrimitiveType();
211 if (Primitive::ComponentSize(type) < n) {
212 break;
213 }
214 if (!IsAligned<n>(field_offset->Uint32Value())) {
215 MemberOffset old_offset = *field_offset;
216 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
217 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
218 }
219 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
220 grouped_and_sorted_fields->pop_front();
221 fields->Set<false>(*current_field_idx, field);
222 if (!gaps->empty() && gaps->top().size >= n) {
223 FieldGap gap = gaps->top();
224 gaps->pop();
225 DCHECK(IsAligned<n>(gap.start_offset));
226 field->SetOffset(MemberOffset(gap.start_offset));
227 if (gap.size > n) {
228 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
229 }
230 } else {
231 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
232 field->SetOffset(*field_offset);
233 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
234 }
235 ++(*current_field_idx);
236 }
237}
238
Elliott Hughes418d20f2011-09-22 14:00:39 -0700239const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700240 "Ljava/lang/Class;",
241 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700242 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700243 "[Ljava/lang/Object;",
244 "Ljava/lang/String;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700245 "Ljava/lang/DexCache;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700246 "Ljava/lang/ref/Reference;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700247 "Ljava/lang/reflect/ArtField;",
248 "Ljava/lang/reflect/ArtMethod;",
Ian Rogers466bb252011-10-14 03:29:56 -0700249 "Ljava/lang/reflect/Proxy;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700250 "[Ljava/lang/String;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700251 "[Ljava/lang/reflect/ArtField;",
252 "[Ljava/lang/reflect/ArtMethod;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700253 "Ljava/lang/ClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800254 "Ljava/lang/Throwable;",
jeffhao8cd6dda2012-02-22 10:15:34 -0800255 "Ljava/lang/ClassNotFoundException;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700256 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700257 "Z",
258 "B",
259 "C",
260 "D",
261 "F",
262 "I",
263 "J",
264 "S",
265 "V",
266 "[Z",
267 "[B",
268 "[C",
269 "[D",
270 "[F",
271 "[I",
272 "[J",
273 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700274 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700275};
276
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800277ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700278 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700279 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700280 dex_cache_image_class_lookup_required_(false),
281 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800282 class_roots_(nullptr),
283 array_iftable_(nullptr),
284 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700285 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800286 log_new_dex_caches_roots_(false),
287 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700288 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800289 portable_resolution_trampoline_(nullptr),
290 quick_resolution_trampoline_(nullptr),
291 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800292 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100293 quick_generic_jni_trampoline_(nullptr),
294 quick_to_interpreter_bridge_trampoline_(nullptr) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700295 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Ian Rogers98379392014-02-24 16:53:16 -0800296 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700297}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700298
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700299// To set a value for generic JNI. May be necessary in compiler tests.
300extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*);
Alex Light64ad14d2014-08-19 14:23:13 -0700301extern "C" void art_quick_resolution_trampoline(mirror::ArtMethod*);
302extern "C" void art_quick_imt_conflict_trampoline(mirror::ArtMethod*);
303extern "C" void art_quick_to_interpreter_bridge(mirror::ArtMethod*);
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700304
Alex Light64ad14d2014-08-19 14:23:13 -0700305void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800306 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700307 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700308
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700309 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700310
Elliott Hughes30646832011-10-13 16:59:46 -0700311 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700312 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700313 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700314 // 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 -0800315 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700316 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
317 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700318 heap->AllocNonMovableObject<true>(self, nullptr,
319 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700320 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700321 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700322 mirror::Class::SetClassClass(java_lang_Class.Get());
323 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700324 if (kUseBakerOrBrooksReadBarrier) {
325 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800326 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700327 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700328 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800329 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800330 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700331
Elliott Hughes418d20f2011-09-22 14:00:39 -0700332 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700333 Handle<mirror::Class> class_array_class(hs.NewHandle(
334 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700335 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700336
Ian Rogers23435d02012-09-24 11:23:12 -0700337 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700338 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
339 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700340 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700341 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700342 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700343 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700344
Ian Rogers23435d02012-09-24 11:23:12 -0700345 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700346 Handle<mirror::Class> object_array_class(hs.NewHandle(
347 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700348 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700349
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700350 // Setup the char (primitive) class to be used for char[].
351 Handle<mirror::Class> char_class(hs.NewHandle(
352 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700353 // The primitive char class won't be initialized by
354 // InitializePrimitiveClass until line 459, but strings (and
355 // internal char arrays) will be allocated before that and the
356 // component size, which is computed from the primitive type, needs
357 // to be set here.
358 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700359
Ian Rogers23435d02012-09-24 11:23:12 -0700360 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700361 Handle<mirror::Class> char_array_class(hs.NewHandle(
362 AllocClass(self, java_lang_Class.Get(),
363 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700364 char_array_class->SetComponentType(char_class.Get());
365 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700366
Ian Rogers23435d02012-09-24 11:23:12 -0700367 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700368 Handle<mirror::Class> java_lang_String(hs.NewHandle(
369 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700370 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700371 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700372 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400373
Fred Shih4ee7a662014-07-11 09:59:27 -0700374 // Setup Reference.
375 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
376 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
377 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
378 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
379 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
380
Ian Rogers23435d02012-09-24 11:23:12 -0700381 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700382 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
383 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
384 kClassRootsMax));
385 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700386 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
387 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
388 SetClassRoot(kClassArrayClass, class_array_class.Get());
389 SetClassRoot(kObjectArrayClass, object_array_class.Get());
390 SetClassRoot(kCharArrayClass, char_array_class.Get());
391 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700392 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700393
394 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700395 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
396 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
397 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
398 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
399 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
400 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
401 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
402 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403
Ian Rogers23435d02012-09-24 11:23:12 -0700404 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700405 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406
Ian Rogers23435d02012-09-24 11:23:12 -0700407 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700408 Handle<mirror::Class> int_array_class(hs.NewHandle(
409 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700410 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700411 mirror::IntArray::SetArrayClass(int_array_class.Get());
412 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700414 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700415
Ian Rogers52813c92012-10-11 11:50:38 -0700416 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700417 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
418 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700419 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700420 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700421 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422
Brian Carlstromf3632832014-05-20 15:36:53 -0700423 // Constructor, Field, Method, and AbstractMethod are necessary so
424 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700425 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
426 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700427 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700428 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700429 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700430 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700431 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700432
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700433 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
434 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700435 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700436 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700437 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700438 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700439
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700440 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700441
442 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700443 Handle<mirror::Class> object_array_string(hs.NewHandle(
444 AllocClass(self, java_lang_Class.Get(),
445 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700446 object_array_string->SetComponentType(java_lang_String.Get());
447 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700448
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700449 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
450 AllocClass(self, java_lang_Class.Get(),
451 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700452 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
453 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700454
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700455 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
456 AllocClass(self, java_lang_Class.Get(),
457 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700458 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
459 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700460
Ian Rogers23435d02012-09-24 11:23:12 -0700461 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
462 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
463 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700464 CHECK_NE(0U, boot_class_path.size());
465 for (size_t i = 0; i != boot_class_path.size(); ++i) {
466 const DexFile* dex_file = boot_class_path[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700467 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700468 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700469 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470
471 // now we can use FindSystemClass
472
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700473 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700474 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
475 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700476
Jeff Hao88474b42013-10-23 16:24:40 -0700477 // Create runtime resolution and imt conflict methods. Also setup the default imt.
478 Runtime* runtime = Runtime::Current();
479 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
480 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
481 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
482
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700483 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
484 // we do not need friend classes or a publicly exposed setter.
485 quick_generic_jni_trampoline_ = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
Alex Light64ad14d2014-08-19 14:23:13 -0700486 if (!runtime->IsCompiler()) {
487 // We need to set up the generic trampolines since we don't have an image.
488 quick_resolution_trampoline_ = reinterpret_cast<void*>(art_quick_resolution_trampoline);
489 quick_imt_conflict_trampoline_ = reinterpret_cast<void*>(art_quick_imt_conflict_trampoline);
490 quick_to_interpreter_bridge_trampoline_ = reinterpret_cast<void*>(art_quick_to_interpreter_bridge);
491 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700492
Mathieu Chartier66f19252012-09-18 08:57:04 -0700493 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700494 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800495 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700496 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700497 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700498 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800499 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700500 std::ostringstream os1, os2;
501 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
502 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
503 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
504 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700505 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800506 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700507 CHECK_EQ(java_lang_String.Get(), String_class);
508 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700509 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700510
Ian Rogers23435d02012-09-24 11:23:12 -0700511 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800512 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800513 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700514
Ian Rogers98379392014-02-24 16:53:16 -0800515 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800516 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700517
Ian Rogers98379392014-02-24 16:53:16 -0800518 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700519 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700520
Ian Rogers98379392014-02-24 16:53:16 -0800521 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800522 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700523
Ian Rogers98379392014-02-24 16:53:16 -0800524 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700525 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700526
Ian Rogers98379392014-02-24 16:53:16 -0800527 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800528 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700529
Ian Rogers98379392014-02-24 16:53:16 -0800530 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800531 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700532
Ian Rogers98379392014-02-24 16:53:16 -0800533 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800534 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700535
Ian Rogers98379392014-02-24 16:53:16 -0800536 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700537 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700538
Ian Rogers98379392014-02-24 16:53:16 -0800539 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700540 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700541
Ian Rogers23435d02012-09-24 11:23:12 -0700542 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800543 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700544 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800545 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700546 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700547 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
548 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700549 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700550 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700551 array_iftable->SetInterface(0, java_lang_Cloneable);
552 array_iftable->SetInterface(1, java_io_Serializable);
553 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554
Ian Rogers23435d02012-09-24 11:23:12 -0700555 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700556 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
557 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
558 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
559 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700560 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700561 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800562 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700563 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700564
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700565 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800566 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700567 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700568
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700569 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800570 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700571 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572
Brian Carlstromf3632832014-05-20 15:36:53 -0700573 mirror::Class* String_array_class =
574 FindSystemClass(self, class_roots_descriptors_[kJavaLangStringArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700575 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700576
Brian Carlstromea46f952013-07-30 01:26:50 -0700577 mirror::Class* Art_method_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800578 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700579 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700580
Brian Carlstromea46f952013-07-30 01:26:50 -0700581 mirror::Class* Art_field_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800582 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700583 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700584
Ian Rogers23435d02012-09-24 11:23:12 -0700585 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700586
Ian Rogers23435d02012-09-24 11:23:12 -0700587 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800588 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700589 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
590
Brian Carlstrom1f870082011-08-23 16:02:11 -0700591 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700592 // finish initializing Reference class
593 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
594 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
595 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
596 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
597 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700598 mirror::Class* java_lang_ref_FinalizerReference =
599 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700600 java_lang_ref_FinalizerReference->SetAccessFlags(
601 java_lang_ref_FinalizerReference->GetAccessFlags() |
602 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700603 mirror::Class* java_lang_ref_PhantomReference =
604 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700605 java_lang_ref_PhantomReference->SetAccessFlags(
606 java_lang_ref_PhantomReference->GetAccessFlags() |
607 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700608 mirror::Class* java_lang_ref_SoftReference =
609 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700610 java_lang_ref_SoftReference->SetAccessFlags(
611 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700612 mirror::Class* java_lang_ref_WeakReference =
613 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700614 java_lang_ref_WeakReference->SetAccessFlags(
615 java_lang_ref_WeakReference->GetAccessFlags() |
616 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700617
Ian Rogers23435d02012-09-24 11:23:12 -0700618 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800619 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700620 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700621 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
622
jeffhao8cd6dda2012-02-22 10:15:34 -0800623 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700624 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800625 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800626 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700627 SetClassRoot(kJavaLangClassNotFoundException,
628 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800629 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700630 SetClassRoot(kJavaLangStackTraceElementArrayClass,
631 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800632 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700633
Ian Rogers98379392014-02-24 16:53:16 -0800634 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700635
Brian Carlstroma004aa92012-02-08 18:05:09 -0800636 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700637}
638
Ian Rogers98379392014-02-24 16:53:16 -0800639void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800640 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700641
642 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700643 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700644 // as the types of the field can't be resolved prior to the runtime being
645 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800646 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700647 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800648 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800649
Brian Carlstromea46f952013-07-30 01:26:50 -0700650 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700651 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
652 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700653
Brian Carlstromea46f952013-07-30 01:26:50 -0700654 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700655 CHECK_STREQ(queue->GetName(), "queue");
656 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700657
Brian Carlstromea46f952013-07-30 01:26:50 -0700658 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700659 CHECK_STREQ(queueNext->GetName(), "queueNext");
660 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700661
Brian Carlstromea46f952013-07-30 01:26:50 -0700662 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700663 CHECK_STREQ(referent->GetName(), "referent");
664 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700665
Brian Carlstromea46f952013-07-30 01:26:50 -0700666 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700667 CHECK_STREQ(zombie->GetName(), "zombie");
668 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700669
Brian Carlstroma663ea52011-08-19 23:33:41 -0700670 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700671 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700672 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800673 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700674 CHECK(klass != nullptr);
675 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700676 // note SetClassRoot does additional validation.
677 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700678 }
679
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700680 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700681
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700682 // disable the slow paths in FindClass and CreatePrimitiveClass now
683 // that Object, Class, and Object[] are setup
684 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700685
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800686 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700687}
688
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700689void ClassLinker::RunRootClinits() {
690 Thread* self = Thread::Current();
691 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800692 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700693 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700694 StackHandleScope<1> hs(self);
695 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700696 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700697 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700698 }
699 }
700}
701
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700702bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800703 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000704 const char* oat_cache_filename,
705 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700706 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700707 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800708
Ian Rogers1d54e732013-05-02 21:10:01 -0700709 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800710 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700711 if (heap->GetImageSpace() == nullptr) {
712 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
713 // out of space anyway it might not matter.
714 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
715 "without an image.", dex_filename);
716 return false;
717 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700718 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800719
Brian Carlstrom6449c622014-02-10 23:48:36 -0800720 std::string dex_file_option("--dex-file=");
721 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800722
Brian Carlstrom6449c622014-02-10 23:48:36 -0800723 std::string oat_fd_option("--oat-fd=");
724 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800725
Brian Carlstrom6449c622014-02-10 23:48:36 -0800726 std::string oat_location_option("--oat-location=");
727 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800728
Brian Carlstrom6449c622014-02-10 23:48:36 -0800729 std::vector<std::string> argv;
730 argv.push_back(dex2oat);
731 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800732 argv.push_back("-classpath");
733 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800734 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800735
Ian Rogers8afeb852014-04-02 14:55:49 -0700736 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800737
Jeff Hao4a200f52014-04-01 14:58:49 -0700738 if (!Runtime::Current()->IsVerificationEnabled()) {
739 argv.push_back("--compiler-filter=verify-none");
740 }
741
Alex Light6e183f22014-07-18 14:57:04 -0700742 if (Runtime::Current()->MustRelocateIfPossible()) {
743 argv.push_back("--runtime-arg");
744 argv.push_back("-Xrelocate");
745 } else {
746 argv.push_back("--runtime-arg");
747 argv.push_back("-Xnorelocate");
748 }
749
Brian Carlstrom6449c622014-02-10 23:48:36 -0800750 if (!kIsTargetBuild) {
751 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700752 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700753
Brian Carlstrom6449c622014-02-10 23:48:36 -0800754 argv.push_back(boot_image_option);
755 argv.push_back(dex_file_option);
756 argv.push_back(oat_fd_option);
757 argv.push_back(oat_location_option);
758 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800759 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800760 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700761 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800762
763 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700764}
765
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700766const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700767 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800768 if (kIsDebugBuild) {
769 for (size_t i = 0; i < oat_files_.size(); ++i) {
770 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700771 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800772 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700773 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
774 oat_files_.push_back(oat_file);
775 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800776}
777
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700778OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
779 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700780 OatFile* oat_file = space->ReleaseOatFile();
781 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700782 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700783 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700784}
785
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100786const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800787 const char* dex_location = dex_file.GetLocation().c_str();
788 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100789 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800790}
791
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100792const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
793 const char* dex_location,
794 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700795 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100796 for (const OatFile* oat_file : oat_files_) {
797 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700798
799 if (oat_location != nullptr) {
800 if (oat_file->GetLocation() != oat_location) {
801 continue;
802 }
803 }
804
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700805 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800806 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700807 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100808 if (oat_dex_file != nullptr) {
809 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800810 }
811 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100812 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800813}
814
Calin Juravle621962a2014-09-02 15:53:55 +0100815
816// Loads all multi dex files from the given oat file returning true on success.
817//
818// Parameters:
819// oat_file - the oat file to load from
820// dex_location - the dex location used to generate the oat file
821// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
822// generated - whether or not the oat_file existed before or was just (re)generated
823// error_msgs - any error messages will be appended here
824// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
825static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
826 const char* dex_location,
827 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700828 bool generated,
829 std::vector<std::string>* error_msgs,
830 std::vector<const DexFile*>* dex_files) {
831 if (oat_file == nullptr) {
832 return false;
833 }
834
835 size_t old_size = dex_files->size(); // To rollback on error.
836
837 bool success = true;
838 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100839 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700840 const char* next_name = next_name_str.c_str();
841
Calin Juravle621962a2014-09-02 15:53:55 +0100842 uint32_t next_location_checksum;
843 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700844 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100845 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
846 // When i=0 the multidex name should be the same as the location name. We already have the
847 // checksum it so we don't need to recompute it.
848 if (dex_location_checksum == nullptr) {
849 next_location_checksum_pointer = nullptr;
850 } else {
851 next_location_checksum = *dex_location_checksum;
852 }
853 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700854 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100855 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700856 }
857
858 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
859
860 if (oat_dex_file == nullptr) {
861 if (i == 0 && generated) {
862 std::string error_msg;
863 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100864 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700865 oat_file->GetLocation().c_str());
866 error_msgs->push_back(error_msg);
867 }
868 break; // Not found, done.
869 }
870
871 // Checksum test. Test must succeed when generated.
872 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100873 if (next_location_checksum_pointer != nullptr) {
874 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700875 }
876
877 if (success) {
878 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
879 if (dex_file == nullptr) {
880 success = false;
881 error_msgs->push_back(error_msg);
882 } else {
883 dex_files->push_back(dex_file);
884 }
885 }
886
887 // When we generated the file, we expect success, or something is terribly wrong.
888 CHECK_EQ(false, generated && !success)
889 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100890 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700891 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
892 }
893
894 if (dex_files->size() == old_size) {
895 success = false; // We did not even find classes.dex
896 }
897
898 if (success) {
899 return true;
900 } else {
901 // Free all the dex files we have loaded.
902 auto it = dex_files->begin() + old_size;
903 auto it_end = dex_files->end();
904 for (; it != it_end; it++) {
905 delete *it;
906 }
907 dex_files->erase(dex_files->begin() + old_size, it_end);
908
909 return false;
910 }
911}
912
913// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
914// complicates the loading process, as we should not use an iterative loading process, because that
915// would register the oat file and dex files that come before the broken one. Instead, check all
916// multidex ahead of time.
917bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
918 std::vector<std::string>* error_msgs,
919 std::vector<const DexFile*>* dex_files) {
920 // 1) Check whether we have an open oat file.
921 // This requires a dex checksum, use the "primary" one.
922 uint32_t dex_location_checksum;
923 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
924 bool have_checksum = true;
925 std::string checksum_error_msg;
926 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100927 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700928 dex_location_checksum_pointer = nullptr;
929 have_checksum = false;
930 }
931
932 bool needs_registering = false;
933
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100934 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
935 dex_location_checksum_pointer);
936 std::unique_ptr<const OatFile> open_oat_file(
937 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700938
939 // 2) If we do not have an open one, maybe there's one on disk already.
940
941 // In case the oat file is not open, we play a locking game here so
942 // that if two different processes race to load and register or generate
943 // (or worse, one tries to open a partial generated file) we will be okay.
944 // This is actually common with apps that use DexClassLoader to work
945 // around the dex method reference limit and that have a background
946 // service running in a separate process.
947 ScopedFlock scoped_flock;
948
949 if (open_oat_file.get() == nullptr) {
950 if (oat_location != nullptr) {
951 // Can only do this if we have a checksum, else error.
952 if (!have_checksum) {
953 error_msgs->push_back(checksum_error_msg);
954 return false;
955 }
956
957 std::string error_msg;
958
959 // We are loading or creating one in the future. Time to set up the file lock.
960 if (!scoped_flock.Init(oat_location, &error_msg)) {
961 error_msgs->push_back(error_msg);
962 return false;
963 }
964
Alex Lighta59dd802014-07-02 16:28:08 -0700965 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700966 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
967 oat_location, &error_msg));
968
969 if (open_oat_file.get() == nullptr) {
970 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
971 dex_location, oat_location, error_msg.c_str());
972 VLOG(class_linker) << compound_msg;
973 error_msgs->push_back(compound_msg);
974 }
975 } else {
976 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100977 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700978 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
979 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100980 kRuntimeISA, error_msgs,
981 &obsolete_file_cleanup_failed));
982 // There's no point in going forward and eventually try to regenerate the
983 // file if we couldn't remove the obsolete one. Mostly likely we will fail
984 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100985 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
986 if (obsolete_file_cleanup_failed) {
987 return false;
988 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700989 }
990 needs_registering = true;
991 }
992
993 // 3) If we have an oat file, check all contained multidex files for our dex_location.
994 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100995 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
996 dex_location_checksum_pointer,
997 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700998 if (success) {
999 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
1000 if (needs_registering) {
1001 // We opened the oat file, so we must register it.
1002 RegisterOatFile(oat_file);
1003 }
Alex Light9dcc4572014-08-14 14:16:26 -07001004 // If the file isn't executable we failed patchoat but did manage to get the dex files.
1005 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -07001006 } else {
1007 if (needs_registering) {
1008 // We opened it, delete it.
1009 open_oat_file.reset();
1010 } else {
1011 open_oat_file.release(); // Do not delete open oat files.
1012 }
1013 }
1014
1015 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
1016
1017 // Need a checksum, fail else.
1018 if (!have_checksum) {
1019 error_msgs->push_back(checksum_error_msg);
1020 return false;
1021 }
1022
1023 // Look in cache location if no oat_location is given.
1024 std::string cache_location;
1025 if (oat_location == nullptr) {
1026 // Use the dalvik cache.
1027 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
1028 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
1029 oat_location = cache_location.c_str();
1030 }
1031
Alex Light64ad14d2014-08-19 14:23:13 -07001032 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -07001033 // Definitely need to lock now.
1034 if (!scoped_flock.HasFile()) {
1035 std::string error_msg;
1036 if (!scoped_flock.Init(oat_location, &error_msg)) {
1037 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -07001038 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -07001039 }
1040 }
1041
Alex Light64ad14d2014-08-19 14:23:13 -07001042 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001043 // Create the oat file.
1044 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1045 oat_location, error_msgs));
1046 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001047
1048 // Failed, bail.
1049 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001050 std::string error_msg;
1051 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1052 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1053 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001054 return false;
1055 }
1056
1057 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001058 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1059 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001060 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001061 if (success) {
1062 RegisterOatFile(open_oat_file.release());
1063 return true;
1064 } else {
1065 return false;
1066 }
1067}
1068
1069const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1070 uint32_t dex_location_checksum,
1071 const char* oat_location,
1072 std::string* error_msg) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001073 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001074 !Runtime::Current()->IsCompiler(),
1075 error_msg));
1076 if (oat_file.get() == nullptr) {
1077 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1078 error_msg->c_str());
1079 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001080 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001081 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001082 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1083 if (image_space != nullptr) {
1084 const ImageHeader& image_header = image_space->GetImageHeader();
1085 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1086 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1087 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1088 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1089 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1090 actual_image_oat_checksum);
1091 return nullptr;
1092 }
1093
1094 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1095 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1096 if (expected_image_oat_offset != actual_image_oat_offset) {
1097 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1098 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1099 actual_image_oat_offset);
1100 return nullptr;
1101 }
1102 int32_t expected_patch_delta = image_header.GetPatchDelta();
1103 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1104 if (expected_patch_delta != actual_patch_delta) {
1105 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1106 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1107 return nullptr;
1108 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001109 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001110
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001111 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1112 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001113 if (oat_dex_file == nullptr) {
1114 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1115 dex_location);
1116 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001117 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001118 uint32_t expected_dex_checksum = dex_location_checksum;
1119 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1120 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001121 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1122 "found 0x%x", oat_location, expected_dex_checksum,
1123 actual_dex_checksum);
1124 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001125 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001126 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1127 if (dex_file.get() != nullptr) {
1128 return oat_file.release();
1129 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001130 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001131 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001132}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001133
Andreas Gampe833a4852014-05-21 18:46:59 -07001134const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1135 int fd, const char* oat_location,
1136 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001137 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001138 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001139 std::string error_msg;
1140 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001141 CHECK(!error_msg.empty());
1142 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001143 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001144 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001145 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001146 !Runtime::Current()->IsCompiler(),
1147 &error_msg));
1148 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001149 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1150 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001151 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001152 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001153 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001154
1155 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001156}
1157
Alex Light6e183f22014-07-18 14:57:04 -07001158bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1159 const InstructionSet instruction_set) {
1160 Runtime* runtime = Runtime::Current();
1161 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001162 if (image_space == nullptr) {
1163 return false;
1164 }
Alex Light6e183f22014-07-18 14:57:04 -07001165 uint32_t image_oat_checksum = 0;
1166 if (instruction_set == kRuntimeISA) {
1167 const ImageHeader& image_header = image_space->GetImageHeader();
1168 image_oat_checksum = image_header.GetOatChecksum();
1169 } else {
1170 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1171 image_space->GetImageLocation().c_str(), instruction_set));
1172 image_oat_checksum = image_header->GetOatChecksum();
1173 }
1174 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1175}
1176
1177bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1178 const InstructionSet instruction_set,
1179 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001180 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001181 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001182 if (image_space == nullptr) {
1183 *error_msg = "No image space for verification against";
1184 return false;
1185 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001186
1187 // If the requested instruction set is the same as the current runtime,
1188 // we can use the checksums directly. If it isn't, we'll have to read the
1189 // image header from the image for the right instruction set.
1190 uint32_t image_oat_checksum = 0;
1191 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001192 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001193 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001194 const ImageHeader& image_header = image_space->GetImageHeader();
1195 image_oat_checksum = image_header.GetOatChecksum();
1196 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001197 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001198 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001199 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001200 image_space->GetImageLocation().c_str(), instruction_set));
1201 image_oat_checksum = image_header->GetOatChecksum();
1202 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001203 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001204 }
1205 const OatHeader& oat_header = oat_file->GetOatHeader();
Alex Light6e183f22014-07-18 14:57:04 -07001206 bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1207 && (oat_header.GetImagePatchDelta() == image_patch_delta)
1208 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1209 if (!ret) {
1210 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1211 oat_file->GetLocation().c_str(),
1212 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1213 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1214 oat_file->GetOatHeader().GetImagePatchDelta(),
1215 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1216 }
1217 return ret;
1218}
1219
1220bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1221 const char* dex_location,
1222 uint32_t dex_location_checksum,
1223 const InstructionSet instruction_set,
1224 std::string* error_msg) {
1225 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1226 return false;
1227 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001228
Brian Carlstromf3632832014-05-20 15:36:53 -07001229 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1230 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001231 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001232 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1233 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001234 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1235 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001236 oat_file->GetLocation().c_str(),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001237 oat_dex_file->GetDexFileLocation().c_str(),
1238 oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001239 }
1240 return false;
1241 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001242
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001243 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001244 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001245}
1246
Alex Lighta59dd802014-07-02 16:28:08 -07001247bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1248 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001249 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001250 std::string* error_msg) {
1251 CHECK(oat_file != nullptr);
1252 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001253 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001254 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001255 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1256 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1257 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001258 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001259 if (oat_dex_file == nullptr) {
1260 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001261 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001262 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001263 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001264 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001265 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001266 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001267 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001268 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001269 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001270 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001271 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001272 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001273 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001274 }
Alex Lighta59dd802014-07-02 16:28:08 -07001275 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001276}
1277
Andreas Gampe833a4852014-05-21 18:46:59 -07001278const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001279 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001280 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001281 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001282 std::vector<std::string>* error_msgs,
1283 bool* obsolete_file_cleanup_failed) {
1284 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001285 bool already_opened = false;
1286 std::string dex_location_str(dex_location);
1287 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1288 &already_opened,
1289 obsolete_file_cleanup_failed,
1290 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001291 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001292 if (oat_file.get() == nullptr) {
1293 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1294 dex_location));
1295 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001296 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001297 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1298 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001299 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1300 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001301 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001302 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001303 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001304 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001305 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1306 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1307 "dex location '%s'. Image checksum incorrect.",
1308 oat_file->GetLocation().c_str(), dex_location));
1309 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001310 } else {
1311 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001312 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001313}
1314
Brian Carlstromae826982011-11-09 01:33:42 -08001315const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001316 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001317 for (size_t i = 0; i < oat_files_.size(); i++) {
1318 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001319 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001320 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001321 return oat_file;
1322 }
1323 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001324 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001325}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001326
Alex Lighta59dd802014-07-02 16:28:08 -07001327const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1328 InstructionSet isa,
1329 bool *already_opened,
1330 bool *obsolete_file_cleanup_failed,
1331 std::vector<std::string>* error_msgs) {
1332 // Find out if we've already opened the file
1333 const OatFile* ret = nullptr;
1334 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1335 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1336 if (ret != nullptr) {
1337 *already_opened = true;
1338 return ret;
1339 }
1340
1341 std::string dalvik_cache;
1342 bool have_android_data = false;
1343 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001344 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001345 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001346 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001347 std::string cache_filename;
1348 if (have_dalvik_cache) {
1349 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1350 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1351 if (ret != nullptr) {
1352 *already_opened = true;
1353 return ret;
1354 }
1355 } else {
1356 // If we need to relocate we should just place odex back where it started.
1357 cache_filename = odex_filename;
1358 }
1359
1360 ret = nullptr;
1361
1362 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1363 //
1364 // Now we do the following:
1365 // 1) Try and open the odex version
1366 // 2) If present, checksum-verified & relocated correctly return it
1367 // 3) Close the odex version to free up its address space.
1368 // 4) Try and open the cache version
1369 // 5) If present, checksum-verified & relocated correctly return it
1370 // 6) Close the cache version to free up its address space.
1371 // 7) If we should relocate:
1372 // a) If we have opened and checksum-verified the odex version relocate it to
1373 // 'cache_filename' and return it
1374 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1375 // it. This should not happen often (I think only the run-test's will hit this case).
1376 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1377 // this point.
1378 // 9) Return nullptr
1379
1380 *already_opened = false;
1381 const Runtime* runtime = Runtime::Current();
1382 CHECK(runtime != nullptr);
1383 bool executable = !runtime->IsCompiler();
1384
1385 std::string odex_error_msg;
1386 bool should_patch_system = false;
1387 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001388 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001389 {
1390 // There is a high probability that these both these oat files map similar/the same address
1391 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001392 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001393 executable, &odex_error_msg));
1394 if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1395 &odex_checksum_verified,
1396 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001397 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001398 } else {
1399 if (odex_checksum_verified) {
1400 // We can just relocate
1401 should_patch_system = true;
1402 odex_error_msg = "Image Patches are incorrect";
1403 }
1404 if (odex_oat_file.get() != nullptr) {
1405 have_system_odex = true;
1406 }
Alex Lighta59dd802014-07-02 16:28:08 -07001407 }
1408 }
1409
Alex Lighta59dd802014-07-02 16:28:08 -07001410 std::string cache_error_msg;
1411 bool should_patch_cache = false;
1412 bool cache_checksum_verified = false;
1413 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001414 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001415 executable, &cache_error_msg));
1416 if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1417 &cache_checksum_verified,
1418 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001419 return cache_oat_file.release();
1420 } else if (cache_checksum_verified) {
1421 // We can just relocate
1422 should_patch_cache = true;
1423 cache_error_msg = "Image Patches are incorrect";
1424 }
1425 } else if (have_android_data) {
1426 // dalvik_cache does not exist but android data does. This means we should be able to create
1427 // it, so we should try.
1428 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1429 }
1430
1431 ret = nullptr;
1432 std::string error_msg;
1433 if (runtime->CanRelocate()) {
1434 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001435 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1436 if (space != nullptr) {
1437 const std::string& image_location = space->GetImageLocation();
1438 if (odex_checksum_verified && should_patch_system) {
1439 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1440 } else if (cache_checksum_verified && should_patch_cache) {
1441 CHECK(have_dalvik_cache);
1442 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1443 }
Alex Light84d76052014-08-22 17:49:35 -07001444 } else if (have_system_odex) {
1445 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001446 }
1447 }
1448 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1449 // implicitly: were able to fine where the cached version is but we were unable to use it,
1450 // either as a destination for relocation or to open a file. We should delete it if it is
1451 // there.
1452 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1453 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1454 "searching for dex file %s: %s",
1455 cache_filename.c_str(), dex_location.c_str(),
1456 strerror(errno));
1457 error_msgs->push_back(rm_error_msg);
1458 VLOG(class_linker) << rm_error_msg;
1459 // Let the caller know that we couldn't remove the obsolete file.
1460 // This is a good indication that further writes may fail as well.
1461 *obsolete_file_cleanup_failed = true;
1462 }
1463 }
1464 if (ret == nullptr) {
1465 VLOG(class_linker) << error_msg;
1466 error_msgs->push_back(error_msg);
1467 std::string relocation_msg;
1468 if (runtime->CanRelocate()) {
1469 relocation_msg = StringPrintf(" and relocation failed");
1470 }
1471 if (have_dalvik_cache && cache_checksum_verified) {
1472 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1473 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1474 cache_filename.c_str(), cache_error_msg.c_str(),
1475 relocation_msg.c_str());
1476 } else {
1477 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1478 "dalvik_cache availible)%s.", odex_filename.c_str(),
1479 odex_error_msg.c_str(), relocation_msg.c_str());
1480 }
1481 VLOG(class_linker) << error_msg;
1482 error_msgs->push_back(error_msg);
1483 }
1484 return ret;
1485}
1486
Alex Light9dcc4572014-08-14 14:16:26 -07001487const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1488 InstructionSet isa,
1489 std::string* error_msg) {
1490 // We open it non-executable
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001491 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001492 if (output.get() == nullptr) {
1493 return nullptr;
1494 }
Alex Light84d76052014-08-22 17:49:35 -07001495 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1496 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001497 return output.release();
1498 } else {
1499 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1500 oat_path.c_str());
1501 return nullptr;
1502 }
1503}
1504
Alex Lighta59dd802014-07-02 16:28:08 -07001505const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1506 const std::string& output_oat,
1507 const std::string& image_location,
1508 InstructionSet isa,
1509 std::string* error_msg) {
Alex Light64ad14d2014-08-19 14:23:13 -07001510 if (!Runtime::Current()->GetHeap()->HasImageSpace()) {
1511 // We don't have an image space so there is no point in trying to patchoat.
1512 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1513 << "running without an image. Attempting to use oat file for interpretation.";
1514 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1515 }
Alex Light9dcc4572014-08-14 14:16:26 -07001516 if (!Runtime::Current()->IsDex2OatEnabled()) {
1517 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1518 // input_oat but make sure we only do interpretation on it's dex files.
1519 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1520 << "disabled. Attempting to use oat file for interpretation";
1521 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1522 }
Alex Lighta59dd802014-07-02 16:28:08 -07001523 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
1524 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1525
1526 std::string isa_arg("--instruction-set=");
1527 isa_arg += GetInstructionSetString(isa);
1528 std::string input_oat_filename_arg("--input-oat-file=");
1529 input_oat_filename_arg += input_oat;
1530 std::string output_oat_filename_arg("--output-oat-file=");
1531 output_oat_filename_arg += output_oat;
1532 std::string patched_image_arg("--patched-image-location=");
1533 patched_image_arg += image_location;
1534
1535 std::vector<std::string> argv;
1536 argv.push_back(patchoat);
1537 argv.push_back(isa_arg);
1538 argv.push_back(input_oat_filename_arg);
1539 argv.push_back(output_oat_filename_arg);
1540 argv.push_back(patched_image_arg);
1541
1542 std::string command_line(Join(argv, ' '));
1543 LOG(INFO) << "Relocate Oat File: " << command_line;
1544 bool success = Exec(argv, error_msg);
1545 if (success) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001546 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001547 !Runtime::Current()->IsCompiler(), error_msg));
1548 bool checksum_verified = false;
1549 if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1550 return output.release();
1551 } else if (output.get() != nullptr) {
1552 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1553 "but output file '%s' failed verifcation: %s",
1554 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1555 } else {
1556 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1557 "but was unable to open output file '%s': %s",
1558 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1559 }
Alex Light9dcc4572014-08-14 14:16:26 -07001560 } else if (!Runtime::Current()->IsCompiler()) {
1561 // patchoat failed which means we probably don't have enough room to place the output oat file,
1562 // instead of failing we should just run the interpreter from the dex files in the input oat.
1563 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1564 << "for interpretation. patchoat failure was: " << *error_msg;
1565 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001566 } else {
1567 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1568 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1569 error_msg->c_str());
1570 }
1571 return nullptr;
1572}
1573
1574int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1575 Runtime* runtime = Runtime::Current();
1576 int32_t real_patch_delta;
1577 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001578 CHECK(image_space != nullptr);
Alex Lighta59dd802014-07-02 16:28:08 -07001579 if (isa == Runtime::Current()->GetInstructionSet()) {
1580 const ImageHeader& image_header = image_space->GetImageHeader();
1581 real_patch_delta = image_header.GetPatchDelta();
1582 } else {
1583 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1584 image_space->GetImageLocation().c_str(), isa));
1585 real_patch_delta = image_header->GetPatchDelta();
1586 }
1587 const OatHeader& oat_header = oat_file->GetOatHeader();
1588 return real_patch_delta - oat_header.GetImagePatchDelta();
1589}
1590
1591bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1592 bool* checksum_verified,
1593 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001594 Runtime* runtime = Runtime::Current();
Alex Lighta59dd802014-07-02 16:28:08 -07001595 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001596 if (image_space == nullptr) {
1597 *error_msg = "No image space present";
1598 return false;
1599 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001600 uint32_t real_image_checksum;
1601 void* real_image_oat_offset;
1602 int32_t real_patch_delta;
1603 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001604 const ImageHeader& image_header = image_space->GetImageHeader();
1605 real_image_checksum = image_header.GetOatChecksum();
1606 real_image_oat_offset = image_header.GetOatDataBegin();
1607 real_patch_delta = image_header.GetPatchDelta();
1608 } else {
1609 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1610 image_space->GetImageLocation().c_str(), isa));
1611 real_image_checksum = image_header->GetOatChecksum();
1612 real_image_oat_offset = image_header->GetOatDataBegin();
1613 real_patch_delta = image_header->GetPatchDelta();
1614 }
1615
1616 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001617 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001618
1619 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1620 *checksum_verified = oat_image_checksum == real_image_checksum;
1621 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001622 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1623 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001624 }
1625
1626 void* oat_image_oat_offset =
1627 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1628 bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1629 if (!offset_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001630 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1631 real_image_oat_offset, oat_image_oat_offset);
Alex Lighta59dd802014-07-02 16:28:08 -07001632 }
1633
1634 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1635 bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1636 if (!patch_delta_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001637 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, received 0x%x)",
1638 real_patch_delta, oat_patch_delta);
Alex Lighta59dd802014-07-02 16:28:08 -07001639 }
1640
1641 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001642 if (!ret) {
1643 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001644 }
1645 return ret;
1646}
1647
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001648const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1649 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001650 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001651 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001652 return oat_file;
1653 }
1654
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001655 return OatFile::Open(oat_location, oat_location, nullptr, !Runtime::Current()->IsCompiler(),
1656 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001657}
1658
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001659static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001660 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001661 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1662
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001663 DCHECK(obj != nullptr);
1664 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001665
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001666 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001667 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001668 if (!method->IsNative()) {
1669 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1670 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001671 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1672 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001673 }
1674 }
1675 }
1676}
1677
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001678void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001679 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001680 CHECK(!init_done_);
1681
Mathieu Chartier590fee92013-09-13 13:46:47 -07001682 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001683 gc::Heap* heap = Runtime::Current()->GetHeap();
1684 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001685 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001686 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001687 OatFile& oat_file = GetImageOatFile(space);
1688 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1689 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001690 const char* image_file_location = oat_file.GetOatHeader().
1691 GetStoreValueByKey(OatHeader::kImageLocationKey);
1692 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001693 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1694 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001695 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1696 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001697 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001698 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001699 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1700 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1701 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001702
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001703 StackHandleScope<1> hs(self);
1704 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1705 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1706 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001707 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001708
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001709 // Special case of setting up the String class early so that we can test arbitrary objects
1710 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001711 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001712
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001713 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001714 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001715 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001716 StackHandleScope<1> hs(self);
1717 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001718 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001719 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1720 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001721 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001722 std::string error_msg;
1723 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001724 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001725 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001726 << " from within oat file " << oat_file.GetLocation()
1727 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001728 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001729
1730 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1731
1732 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001733 }
1734
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001735 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1736 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001737 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001738
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001739 // Set entry point to interpreter if in InterpretOnly mode.
1740 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001741 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001742 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001743 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001744
1745 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001746 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001747 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001748
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001749 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001750 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1751 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001752 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001753 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001754 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001755 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1756 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1757 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1758 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1759 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1760 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1761 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1762 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1763 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1764 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001765
Ian Rogers98379392014-02-24 16:53:16 -08001766 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001767
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001768 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001769}
1770
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001771void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1772 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1773 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001774 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1775 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001776 }
1777 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1778 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001779 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1780 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1781 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1782 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001783 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1784 // corresponding object. This is slow, but luckily for us, this may only happen with a
1785 // concurrent moving GC.
1786 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1787 it != end && it->first == pair.first; ++it) {
1788 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001789 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1790 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001791 }
1792 }
1793 }
1794 }
1795 }
1796 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1797 new_class_roots_.clear();
1798 }
1799 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1800 log_new_class_table_roots_ = true;
1801 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1802 log_new_class_table_roots_ = false;
1803 }
1804 // We deliberately ignore the class roots in the image since we
1805 // handle image roots by using the MS/CMS rescanning of dirty cards.
1806}
1807
Brian Carlstroma663ea52011-08-19 23:33:41 -07001808// Keep in sync with InitCallback. Anything we visit, we need to
1809// reinit references to when reinitializing a ClassLinker from a
1810// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001811void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001812 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001813 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001814 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001815 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001816 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001817 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1818 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001819 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001820 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1821 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001822 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001823 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001824 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001825 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1826 new_dex_cache_roots_.clear();
1827 }
1828 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1829 log_new_dex_caches_roots_ = true;
1830 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1831 log_new_dex_caches_roots_ = false;
1832 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001833 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001834 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001835 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1836 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001837 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001838 if (!find_array_class_cache_[i].IsNull()) {
1839 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001840 }
1841 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001842}
1843
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001844void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1845 if (dex_cache_image_class_lookup_required_) {
1846 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001847 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001848 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001849 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001850 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1851 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001852 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001853 return;
1854 }
1855 }
1856}
1857
Ian Rogersdbf3be02014-08-29 15:40:08 -07001858static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001859 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001860 classes->insert(c);
1861 return true;
1862}
1863
Ian Rogersdbf3be02014-08-29 15:40:08 -07001864struct GetClassesVisitorArrayArg {
1865 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1866 int32_t index;
1867 bool success;
1868};
1869
1870static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1871 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1872 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1873 if (arg->index < (*arg->classes)->GetLength()) {
1874 (*arg->classes)->Set(arg->index, c);
1875 arg->index++;
1876 return true;
1877 } else {
1878 arg->success = false;
1879 return false;
1880 }
1881}
1882
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001883void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001884 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1885 // is avoiding duplicates.
1886 if (!kMovingClasses) {
1887 std::set<mirror::Class*> classes;
1888 VisitClasses(GetClassesVisitorSet, &classes);
1889 for (mirror::Class* klass : classes) {
1890 if (!visitor(klass, arg)) {
1891 return;
1892 }
1893 }
1894 } else {
1895 Thread* self = Thread::Current();
1896 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001897 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001898 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1899 GetClassesVisitorArrayArg local_arg;
1900 local_arg.classes = &classes;
1901 local_arg.success = false;
1902 // We size the array assuming classes won't be added to the class table during the visit.
1903 // If this assumption fails we iterate again.
1904 while (!local_arg.success) {
1905 size_t class_table_size;
1906 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001907 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001908 class_table_size = class_table_.size();
1909 }
1910 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1911 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1912 classes.Assign(
1913 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1914 CHECK(classes.Get() != nullptr); // OOME.
1915 local_arg.index = 0;
1916 local_arg.success = true;
1917 VisitClasses(GetClassesVisitorArray, &local_arg);
1918 }
1919 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1920 // If the class table shrank during creation of the clases array we expect null elements. If
1921 // the class table grew then the loop repeats. If classes are created after the loop has
1922 // finished then we don't visit.
1923 mirror::Class* klass = classes->Get(i);
1924 if (klass != nullptr && !visitor(klass, arg)) {
1925 return;
1926 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001927 }
1928 }
1929}
1930
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001931ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001932 mirror::Class::ResetClass();
1933 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001934 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001935 mirror::ArtField::ResetClass();
1936 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001937 mirror::BooleanArray::ResetArrayClass();
1938 mirror::ByteArray::ResetArrayClass();
1939 mirror::CharArray::ResetArrayClass();
1940 mirror::DoubleArray::ResetArrayClass();
1941 mirror::FloatArray::ResetArrayClass();
1942 mirror::IntArray::ResetArrayClass();
1943 mirror::LongArray::ResetArrayClass();
1944 mirror::ShortArray::ResetArrayClass();
1945 mirror::Throwable::ResetClass();
1946 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001947 STLDeleteElements(&boot_class_path_);
1948 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001949}
1950
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001951mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001952 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001953 StackHandleScope<16> hs(self);
1954 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1955 Handle<mirror::DexCache> dex_cache(
1956 hs.NewHandle(down_cast<mirror::DexCache*>(
1957 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1958 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001959 if (dex_cache.Get() == nullptr) {
1960 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001961 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001962 Handle<mirror::String>
1963 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001964 if (location.Get() == nullptr) {
1965 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001966 }
Ian Rogers700a4022014-05-19 16:49:03 -07001967 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001968 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001969 if (strings.Get() == nullptr) {
1970 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001971 }
Ian Rogers700a4022014-05-19 16:49:03 -07001972 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001973 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001974 if (types.Get() == nullptr) {
1975 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001976 }
Ian Rogers700a4022014-05-19 16:49:03 -07001977 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001978 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001979 if (methods.Get() == nullptr) {
1980 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001981 }
Ian Rogers700a4022014-05-19 16:49:03 -07001982 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001983 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001984 if (fields.Get() == nullptr) {
1985 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001986 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001987 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1988 fields.Get());
1989 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001990}
1991
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001992mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001993 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001994 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001995 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001996 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001997 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001998 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1999 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002000 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002001 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08002002 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002003 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002004 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002005}
2006
Ian Rogers6fac4472014-02-25 17:01:10 -08002007mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07002008 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002009}
2010
Brian Carlstromea46f952013-07-30 01:26:50 -07002011mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002012 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002013 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07002014}
2015
Brian Carlstromea46f952013-07-30 01:26:50 -07002016mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002017 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002018 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002019}
2020
Mathieu Chartier590fee92013-09-13 13:46:47 -07002021mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2022 Thread* self, size_t length) {
2023 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2024 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002025}
2026
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002027mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2028 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002029 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002030
2031 // For temporary classes we must wait for them to be retired.
2032 if (init_done_ && klass->IsTemp()) {
2033 CHECK(!klass->IsResolved());
2034 if (klass->IsErroneous()) {
2035 ThrowEarlierClassFailure(klass);
2036 return nullptr;
2037 }
2038 StackHandleScope<1> hs(self);
2039 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2040 ObjectLock<mirror::Class> lock(self, h_class);
2041 // Loop and wait for the resolving thread to retire this class.
2042 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2043 lock.WaitIgnoringInterrupts();
2044 }
2045 if (h_class->IsErroneous()) {
2046 ThrowEarlierClassFailure(h_class.Get());
2047 return nullptr;
2048 }
2049 CHECK(h_class->IsRetired());
2050 // Get the updated class from class table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002051 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002052 }
2053
Brian Carlstromaded5f72011-10-07 17:15:04 -07002054 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002055 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002056 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002057 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2058 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002059 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002060 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2061 ThrowClassCircularityError(h_class.Get());
2062 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002063 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002064 }
2065 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002066 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002067 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002068 }
2069 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002070
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002071 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002072 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002073 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002074 }
2075 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002076 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002077 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002078 return klass;
2079}
2080
Ian Rogers68b56852014-08-29 20:19:11 -07002081typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2082
2083// Search a collection of DexFiles for a descriptor
2084ClassPathEntry FindInClassPath(const char* descriptor,
2085 const std::vector<const DexFile*>& class_path) {
2086 for (size_t i = 0; i != class_path.size(); ++i) {
2087 const DexFile* dex_file = class_path[i];
2088 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002089 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002090 return ClassPathEntry(dex_file, dex_class_def);
2091 }
2092 }
2093 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002094 return ClassPathEntry(static_cast<const DexFile*>(nullptr),
2095 static_cast<const DexFile::ClassDef*>(nullptr));
Ian Rogers68b56852014-08-29 20:19:11 -07002096}
2097
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002098mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2099 Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002100 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002101 if (class_loader->GetClass() !=
2102 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2103 class_loader->GetParent()->GetClass() !=
2104 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2105 return nullptr;
2106 }
2107 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2108 // Check if this would be found in the parent boot class loader.
2109 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002110 mirror::Class* klass = LookupClass(self, descriptor, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002111 if (klass != nullptr) {
2112 return EnsureResolved(self, descriptor, klass);
2113 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002114 klass = DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002115 *pair.second);
2116 if (klass != nullptr) {
2117 return klass;
2118 }
2119 CHECK(self->IsExceptionPending()) << descriptor;
2120 self->ClearException();
2121 } else {
2122 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2123 StackHandleScope<3> hs(self);
2124 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2125 // We need to get the DexPathList and loop through it.
2126 Handle<mirror::ArtField> cookie_field =
2127 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2128 Handle<mirror::ArtField> dex_file_field =
2129 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002130 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002131 mirror::Object* dex_path_list =
2132 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2133 GetObject(class_loader.Get());
2134 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2135 cookie_field.Get() != nullptr) {
2136 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2137 mirror::Object* dex_elements_obj =
2138 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2139 GetObject(dex_path_list);
2140 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2141 // at the mCookie which is a DexFile vector.
2142 if (dex_elements_obj != nullptr) {
2143 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2144 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2145 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2146 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2147 if (element == nullptr) {
2148 // Should never happen, fall back to java code to throw a NPE.
2149 break;
2150 }
2151 mirror::Object* dex_file = dex_file_field->GetObject(element);
2152 if (dex_file != nullptr) {
2153 const uint64_t cookie = cookie_field->GetLong(dex_file);
2154 auto* dex_files =
2155 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2156 if (dex_files == nullptr) {
2157 // This should never happen so log a warning.
2158 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2159 break;
2160 }
2161 for (const DexFile* dex_file : *dex_files) {
2162 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
2163 if (dex_class_def != nullptr) {
2164 RegisterDexFile(*dex_file);
2165 mirror::Class* klass =
Ian Rogers7b078e82014-09-10 14:44:24 -07002166 DefineClass(self, descriptor, class_loader, *dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002167 if (klass == nullptr) {
2168 CHECK(self->IsExceptionPending()) << descriptor;
2169 self->ClearException();
2170 return nullptr;
2171 }
2172 return klass;
2173 }
2174 }
2175 }
2176 }
2177 }
2178 }
2179 }
2180 return nullptr;
2181}
2182
Ian Rogers98379392014-02-24 16:53:16 -08002183mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002184 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002185 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002186 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002187 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002188 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002189 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2190 // for primitive classes that aren't backed by dex files.
2191 return FindPrimitiveClass(descriptor[0]);
2192 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002193 // Find the class in the loaded classes table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002194 mirror::Class* klass = LookupClass(self, descriptor, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002195 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002196 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002197 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002198 // Class is not yet loaded.
2199 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08002200 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002201 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002202 // The boot class loader, search the boot class path.
Ian Rogers68b56852014-08-29 20:19:11 -07002203 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2204 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002205 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2206 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002207 } else {
2208 // The boot class loader is searched ahead of the application class loader, failures are
2209 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2210 // trigger the chaining with a proper stack trace.
2211 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2212 self->SetException(ThrowLocation(), pre_allocated);
2213 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002214 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002215 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002216 // First try with the bootstrap class loader.
2217 if (class_loader.Get() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002218 klass = LookupClass(self, descriptor, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002219 if (klass != nullptr) {
2220 return EnsureResolved(self, descriptor, klass);
2221 }
2222 }
Ian Rogers63557452014-06-04 16:57:15 -07002223 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2224 // a NoClassDefFoundError being allocated.
Ian Rogers68b56852014-08-29 20:19:11 -07002225 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2226 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002227 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2228 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002229 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002230 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002231 const std::vector<const DexFile*>* class_path;
2232 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002233 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002234 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002235 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002236 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2237 }
Ian Rogers68b56852014-08-29 20:19:11 -07002238 pair = FindInClassPath(descriptor, *class_path);
2239 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002240 return DefineClass(self, descriptor, class_loader, *pair.first, *pair.second);
2241 } else {
2242 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2243 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2244 self->SetException(ThrowLocation(), pre_allocated);
2245 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002246 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002247 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002248 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002249 mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, class_loader);
2250 if (klass != nullptr) {
2251 return klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002252 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002253 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002254 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002255 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002256 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002257 {
2258 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002259 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2260 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002261 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002262 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002263 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002264 }
Ian Rogers68b56852014-08-29 20:19:11 -07002265 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002266 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2267 WellKnownClasses::java_lang_ClassLoader_loadClass,
2268 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002269 }
Ian Rogers98379392014-02-24 16:53:16 -08002270 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002271 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002272 return nullptr;
2273 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002274 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002275 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002276 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002277 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002278 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002279 // success, return mirror::Class*
2280 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002281 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002282 }
Ian Rogers07140832014-09-30 15:43:59 -07002283 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002284}
2285
Ian Rogers7b078e82014-09-10 14:44:24 -07002286mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002287 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002288 const DexFile& dex_file,
2289 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002290 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002291 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002292 bool should_allocate = false;
2293
Brian Carlstromaded5f72011-10-07 17:15:04 -07002294 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002295 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002296 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002297 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002298 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002299 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002300 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002301 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002302 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002303 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2304 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002305 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002306 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002307 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002308 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002309 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002310 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002311 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002312 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002313 }
2314 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002315 should_allocate = true;
2316 }
2317
2318 if (should_allocate) {
2319 // Allocate a class with the status of not ready.
2320 // Interface object should get the right size here. Regular class will
2321 // figure out the right size later and be replaced with one of the right
2322 // size when the class becomes resolved.
2323 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002324 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002325 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002326 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002327 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002328 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002329 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002330 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002331 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002332 if (self->IsExceptionPending()) {
2333 // An exception occured during load, set status to erroneous while holding klass' lock in case
2334 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002335 if (!klass->IsErroneous()) {
2336 klass->SetStatus(mirror::Class::kStatusError, self);
2337 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002338 return nullptr;
2339 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002340 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002341
Mathieu Chartier590fee92013-09-13 13:46:47 -07002342 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002343 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07002344 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002345 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2346 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002347 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002348 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002349
Brian Carlstromaded5f72011-10-07 17:15:04 -07002350 // Finish loading (if necessary) by finding parents
2351 CHECK(!klass->IsLoaded());
2352 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2353 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002354 if (!klass->IsErroneous()) {
2355 klass->SetStatus(mirror::Class::kStatusError, self);
2356 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002357 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002358 }
2359 CHECK(klass->IsLoaded());
2360 // Link the class (if necessary)
2361 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002362 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002363 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002364
2365 mirror::Class* new_class = nullptr;
2366 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002367 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002368 if (!klass->IsErroneous()) {
2369 klass->SetStatus(mirror::Class::kStatusError, self);
2370 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002371 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002372 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002373 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002374 CHECK(new_class != nullptr) << descriptor;
2375 CHECK(new_class->IsResolved()) << descriptor;
2376
2377 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002378
2379 /*
2380 * We send CLASS_PREPARE events to the debugger from here. The
2381 * definition of "preparation" is creating the static fields for a
2382 * class and initializing them to the standard default values, but not
2383 * executing any code (that comes later, during "initialization").
2384 *
2385 * We did the static preparation in LinkClass.
2386 *
2387 * The class has been prepared and resolved but possibly not yet verified
2388 * at this point.
2389 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002390 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002391
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002392 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002393}
2394
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002395uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2396 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002397 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002398 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002399 size_t num_8 = 0;
2400 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002401 size_t num_32 = 0;
2402 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002403 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002404 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2405 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002406 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002407 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002408 switch (c) {
2409 case 'L':
2410 case '[':
2411 num_ref++;
2412 break;
2413 case 'J':
2414 case 'D':
2415 num_64++;
2416 break;
2417 case 'I':
2418 case 'F':
2419 num_32++;
2420 break;
2421 case 'S':
2422 case 'C':
2423 num_16++;
2424 break;
2425 case 'B':
2426 case 'Z':
2427 num_8++;
2428 break;
2429 default:
2430 LOG(FATAL) << "Unknown descriptor: " << c;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002431 }
2432 }
2433 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002434 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002435}
2436
Ian Rogers97b52f82014-08-14 11:34:07 -07002437OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2438 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002439 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002440 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2441 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002442 *found = false;
2443 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002444 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002445 *found = true;
2446 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002447}
2448
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002449static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2450 uint32_t method_idx) {
2451 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002452 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002453 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002454 ClassDataItemIterator it(dex_file, class_data);
2455 // Skip fields
2456 while (it.HasNextStaticField()) {
2457 it.Next();
2458 }
2459 while (it.HasNextInstanceField()) {
2460 it.Next();
2461 }
2462 // Process methods
2463 size_t class_def_method_index = 0;
2464 while (it.HasNextDirectMethod()) {
2465 if (it.GetMemberIndex() == method_idx) {
2466 return class_def_method_index;
2467 }
2468 class_def_method_index++;
2469 it.Next();
2470 }
2471 while (it.HasNextVirtualMethod()) {
2472 if (it.GetMemberIndex() == method_idx) {
2473 return class_def_method_index;
2474 }
2475 class_def_method_index++;
2476 it.Next();
2477 }
2478 DCHECK(!it.HasNext());
2479 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2480 return 0;
2481}
2482
Ian Rogers97b52f82014-08-14 11:34:07 -07002483const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002484 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002485 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002486 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002487 size_t oat_method_index;
2488 if (method->IsStatic() || method->IsDirect()) {
2489 // Simple case where the oat method index was stashed at load time.
2490 oat_method_index = method->GetMethodIndex();
2491 } else {
2492 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2493 // by search for its position in the declared virtual methods.
2494 oat_method_index = declaring_class->NumDirectMethods();
2495 size_t end = declaring_class->NumVirtualMethods();
2496 bool found = false;
2497 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002498 // Check method index instead of identity in case of duplicate method definitions.
2499 if (method->GetDexMethodIndex() ==
2500 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002501 found = true;
2502 break;
2503 }
Ian Rogersf320b632012-03-13 18:47:47 -07002504 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002505 }
2506 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2507 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002508 DCHECK_EQ(oat_method_index,
2509 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002510 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002511 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002512 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2513 declaring_class->GetDexClassDefIndex(),
2514 found);
2515 if (!found) {
2516 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002517 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002518 *found = true;
2519 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002520}
2521
2522// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002523const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002524 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002525 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002526 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002527 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002528 bool found;
2529 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002530 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002531 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002532 result = oat_method.GetQuickCode();
2533 }
2534
Ian Rogersef7d42f2014-01-06 12:55:46 -08002535 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002536 if (method->IsNative()) {
2537 // No code and native? Use generic trampoline.
2538 result = GetQuickGenericJniTrampoline();
2539 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002540 // No code? Do we expect portable code?
2541 result = GetQuickToPortableBridge();
2542 } else {
2543 // No code? You must mean to go into the interpreter.
2544 result = GetQuickToInterpreterBridge();
2545 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002546 }
2547 return result;
TDYa12785321912012-04-01 15:24:56 -07002548}
2549
Ian Rogersef7d42f2014-01-06 12:55:46 -08002550const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2551 bool* have_portable_code) {
2552 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2553 *have_portable_code = false;
2554 if (method->IsProxyMethod()) {
2555 return GetPortableProxyInvokeHandler();
2556 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002557 bool found;
2558 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002559 const void* result = nullptr;
2560 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002561 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002562 result = oat_method.GetPortableCode();
2563 quick_code = oat_method.GetQuickCode();
2564 }
2565
Ian Rogersef7d42f2014-01-06 12:55:46 -08002566 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002567 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002568 // No code? You must mean to go into the interpreter.
2569 result = GetPortableToInterpreterBridge();
2570 } else {
2571 // No code? But there's quick code, so use a bridge.
2572 result = GetPortableToQuickBridge();
2573 }
2574 } else {
2575 *have_portable_code = true;
2576 }
2577 return result;
2578}
2579
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002580const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2581 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2582 return nullptr;
2583 }
2584 bool found;
2585 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2586 return found ? oat_method.GetQuickCode() : nullptr;
2587}
2588
2589const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2590 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2591 return nullptr;
2592 }
2593 bool found;
2594 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2595 return found ? oat_method.GetPortableCode() : nullptr;
2596}
2597
Ian Rogersef7d42f2014-01-06 12:55:46 -08002598const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2599 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002600 bool found;
2601 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2602 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002603 return nullptr;
2604 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002605 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002606 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002607}
2608
2609const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2610 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002611 bool found;
2612 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2613 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002614 return nullptr;
2615 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002616 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002617 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002618}
2619
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002620// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002621static bool NeedsInterpreter(
2622 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2623 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002624 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002625 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002626 // May return true for native code, in the case of generic JNI
2627 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002628 return true;
2629 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002630#ifdef ART_SEA_IR_MODE
2631 ScopedObjectAccess soa(Thread::Current());
2632 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2633 LOG(INFO) << "Found " << PrettyMethod(method);
2634 return false;
2635 }
2636#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002637 // If interpreter mode is enabled, every method (except native and proxy) must
2638 // be run with interpreter.
2639 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2640 !method->IsNative() && !method->IsProxyMethod();
2641}
2642
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002643void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002644 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002645 if (klass->NumDirectMethods() == 0) {
2646 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002647 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002648 Runtime* runtime = Runtime::Current();
2649 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002650 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2651 return; // OAT file unavailable.
2652 }
Ian Rogers19846512012-02-24 11:42:47 -08002653 }
Alex Light64ad14d2014-08-19 14:23:13 -07002654
Mathieu Chartierf8322842014-05-16 10:59:25 -07002655 const DexFile& dex_file = klass->GetDexFile();
2656 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002657 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002658 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002659 // There should always be class data if there were direct methods.
2660 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002661 ClassDataItemIterator it(dex_file, class_data);
2662 // Skip fields
2663 while (it.HasNextStaticField()) {
2664 it.Next();
2665 }
2666 while (it.HasNextInstanceField()) {
2667 it.Next();
2668 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002669 bool has_oat_class;
2670 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2671 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002672 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002673 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002674 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002675 if (!method->IsStatic()) {
2676 // Only update static methods.
2677 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002678 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002679 const void* portable_code = nullptr;
2680 const void* quick_code = nullptr;
2681 if (has_oat_class) {
2682 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2683 portable_code = oat_method.GetPortableCode();
2684 quick_code = oat_method.GetQuickCode();
2685 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002686 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2687 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002688 if (enter_interpreter) {
2689 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002690 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002691 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2692 quick_code = GetQuickGenericJniTrampoline();
Ian Rogers1a570662014-03-12 01:02:21 -07002693 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002694 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002695 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002696 quick_code = GetQuickToInterpreterBridge();
2697 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002698 } else {
2699 if (portable_code == nullptr) {
2700 portable_code = GetPortableToQuickBridge();
2701 } else {
2702 have_portable_code = true;
2703 }
2704 if (quick_code == nullptr) {
2705 quick_code = GetQuickToPortableBridge();
2706 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002707 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002708 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2709 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002710 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002711 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002712}
2713
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002714void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002715 const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002716 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002717 uint32_t method_index) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002718 if (Runtime::Current()->IsCompiler()) {
2719 // The following code only applies to a non-compiler runtime.
2720 return;
2721 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002722 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002723 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2724 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002725 if (oat_class != nullptr) {
2726 // Every kind of method should at least get an invoke stub from the oat_method.
2727 // non-abstract methods also get their code pointers.
2728 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2729 oat_method.LinkMethod(method.Get());
2730 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002731
Jeff Hao16743632013-05-08 10:59:04 -07002732 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002733 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002734 method->GetEntryPointFromQuickCompiledCode(),
2735 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002736 if (enter_interpreter && !method->IsNative()) {
Ian Rogers848871b2013-08-05 10:56:33 -07002737 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002738 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002739 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002740 }
2741
Brian Carlstrom92827a52011-10-10 15:50:01 -07002742 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002743 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2744 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002745 return;
2746 }
Ian Rogers19846512012-02-24 11:42:47 -08002747
Ian Rogersef7d42f2014-01-06 12:55:46 -08002748 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002749 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002750 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002751 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2752 // after initializing class (see ClassLinker::InitializeClass method).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002753 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline());
2754 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002755 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002756 if (!method->IsNative()) {
2757 // Set entry point from compiled code if there's no code or in interpreter only mode.
2758 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2759 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2760 } else {
2761 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline());
2762 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2763 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002764 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2765 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2766 have_portable_code = true;
2767 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2768 } else {
2769 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2770 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002771 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002772
Ian Rogers62d6c772013-02-27 08:32:07 -08002773 if (method->IsNative()) {
2774 // Unregistering restores the dlsym lookup stub.
2775 method->UnregisterNative(Thread::Current());
Andreas Gampe90546832014-03-12 18:07:19 -07002776
2777 if (enter_interpreter) {
2778 // We have a native method here without code. Then it should have either the GenericJni
2779 // trampoline as entrypoint (non-static), or the Resolution trampoline (static).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002780 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline()
Andreas Gampe9a6a99a2014-03-14 07:52:20 -07002781 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline());
Andreas Gampe90546832014-03-12 18:07:19 -07002782 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002783 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002784
Ian Rogers62d6c772013-02-27 08:32:07 -08002785 // Allow instrumentation its chance to hijack code.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002786 Runtime* runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002787 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002788 method->GetEntryPointFromQuickCompiledCode(),
2789 method->GetEntryPointFromPortableCompiledCode(),
2790 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002791}
2792
Fred Shih37f05ef2014-07-16 18:38:08 -07002793
Fred Shih37f05ef2014-07-16 18:38:08 -07002794
Ian Rogers7b078e82014-09-10 14:44:24 -07002795void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002796 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002797 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002798 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002799 CHECK(klass.Get() != nullptr);
2800 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002801 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002802 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002803 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002804
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002805 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002806 if (kUseBakerOrBrooksReadBarrier) {
2807 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002808 }
Andreas Gampe51829322014-08-25 15:05:04 -07002809 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002810 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002811 klass->SetAccessFlags(access_flags);
2812 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002813 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002814 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002815
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002816 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002817 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002818
Ian Rogers13735952014-10-08 12:43:28 -07002819 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002820 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002821 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002822 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002823
Ian Rogers97b52f82014-08-14 11:34:07 -07002824
2825 bool has_oat_class = false;
2826 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2827 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2828 &has_oat_class);
2829 if (has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002830 LoadClassMembers(self, dex_file, class_data, klass, class_loader, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002831 }
2832 }
2833 if (!has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002834 LoadClassMembers(self, dex_file, class_data, klass, class_loader, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002835 }
2836}
2837
Ian Rogers7b078e82014-09-10 14:44:24 -07002838void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002839 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002840 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002841 mirror::ClassLoader* class_loader,
2842 const OatFile::OatClass* oat_class) {
2843 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002844 ClassDataItemIterator it(dex_file, class_data);
2845 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002846 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002847 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002848 CHECK(self->IsExceptionPending()); // OOME.
2849 return;
2850 }
2851 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002852 }
2853 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002854 mirror::ObjectArray<mirror::ArtField>* fields =
2855 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002856 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002857 CHECK(self->IsExceptionPending()); // OOME.
2858 return;
2859 }
2860 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002861 }
2862 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002863 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002864 StackHandleScope<1> hs(self);
2865 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002866 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002867 CHECK(self->IsExceptionPending()); // OOME.
2868 return;
2869 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002870 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002871 LoadField(dex_file, it, klass, sfield);
2872 }
2873 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002874 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002875 StackHandleScope<1> hs(self);
2876 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002877 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002878 CHECK(self->IsExceptionPending()); // OOME.
2879 return;
2880 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002881 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002882 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002883 }
2884
Ian Rogers0571d352011-11-03 19:51:38 -07002885 // Load methods.
2886 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002887 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002888 mirror::ObjectArray<mirror::ArtMethod>* directs =
2889 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002890 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002891 CHECK(self->IsExceptionPending()); // OOME.
2892 return;
2893 }
2894 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002895 }
Ian Rogers0571d352011-11-03 19:51:38 -07002896 if (it.NumVirtualMethods() != 0) {
2897 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002898 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2899 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002900 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002901 CHECK(self->IsExceptionPending()); // OOME.
2902 return;
2903 }
2904 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002905 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002906 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002907 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2908 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002909 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002910 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002911 StackHandleScope<1> hs(self);
2912 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002913 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002914 CHECK(self->IsExceptionPending()); // OOME.
2915 return;
2916 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002917 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002918 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002919 uint32_t it_method_index = it.GetMemberIndex();
2920 if (last_dex_method_index == it_method_index) {
2921 // duplicate case
2922 method->SetMethodIndex(last_class_def_method_index);
2923 } else {
2924 method->SetMethodIndex(class_def_method_index);
2925 last_dex_method_index = it_method_index;
2926 last_class_def_method_index = class_def_method_index;
2927 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002928 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002929 }
2930 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002931 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002932 StackHandleScope<1> hs(self);
2933 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002934 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002935 CHECK(self->IsExceptionPending()); // OOME.
2936 return;
2937 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002938 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002939 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002940 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002941 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002942 }
2943 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002944}
2945
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002946void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002947 Handle<mirror::Class> klass,
2948 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002949 uint32_t field_idx = it.GetMemberIndex();
2950 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002951 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002952 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002953}
2954
Brian Carlstromea46f952013-07-30 01:26:50 -07002955mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002956 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002957 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002958 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002959 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002960 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002961
Brian Carlstromea46f952013-07-30 01:26:50 -07002962 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002963 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002964 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002965 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002966 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002967 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002968
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002969 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002970 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002971 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002972 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002973
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002974 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002975 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002976 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002977
Andreas Gampe51829322014-08-25 15:05:04 -07002978 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002979
Ian Rogersdfb325e2013-10-30 01:00:44 -07002980 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002981 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002982 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2983 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002984 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002985 klass->SetFinalizable();
2986 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002987 std::string temp;
2988 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002989 // The Enum class declares a "final" finalize() method to prevent subclasses from
2990 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2991 // subclasses, so we exclude it here.
2992 // We also want to avoid setting the flag on Object, where we know that finalize() is
2993 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002994 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2995 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002996 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002997 }
2998 }
2999 }
3000 } else if (method_name[0] == '<') {
3001 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003002 bool is_init = (strcmp("<init>", method_name) == 0);
3003 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003004 if (UNLIKELY(!is_init && !is_clinit)) {
3005 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3006 } else {
3007 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3008 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003009 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003010 access_flags |= kAccConstructor;
3011 }
3012 }
3013 }
3014 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003015
Mathieu Chartier66f19252012-09-18 08:57:04 -07003016 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07003017}
3018
Ian Rogers7b078e82014-09-10 14:44:24 -07003019void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003020 StackHandleScope<1> hs(self);
3021 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003022 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3023 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003024 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003025}
3026
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003027void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003028 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003029 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003030 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003031 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003032}
3033
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003034bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003035 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07003036 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003037 mirror::DexCache* dex_cache = GetDexCache(i);
3038 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08003039 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003040 }
3041 }
3042 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003043}
3044
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003045bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003046 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003047 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003048}
3049
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003050void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003051 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003052 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003053 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003054 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3055 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003056 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003057 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003058 if (log_new_dex_caches_roots_) {
3059 // TODO: This is not safe if we can remove dex caches.
3060 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3061 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003062}
3063
Brian Carlstromaded5f72011-10-07 17:15:04 -07003064void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003065 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003066 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003067 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003068 if (IsDexFileRegisteredLocked(dex_file)) {
3069 return;
3070 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003071 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003072 // Don't alloc while holding the lock, since allocation may need to
3073 // suspend all threads and another thread may need the dex_lock_ to
3074 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003075 StackHandleScope<1> hs(self);
3076 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003077 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3078 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003079 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003080 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003081 if (IsDexFileRegisteredLocked(dex_file)) {
3082 return;
3083 }
3084 RegisterDexFileLocked(dex_file, dex_cache);
3085 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003086}
3087
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003088void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003089 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003090 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003091 RegisterDexFileLocked(dex_file, dex_cache);
3092}
3093
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003094mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003095 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003096 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003097 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003098 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003099 if (dex_cache->GetDexFile() == &dex_file) {
3100 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003101 }
3102 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003103 // Search matching by location name.
3104 std::string location(dex_file.GetLocation());
3105 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003106 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003107 if (dex_cache->GetDexFile()->GetLocation() == location) {
3108 return dex_cache;
3109 }
3110 }
3111 // Failure, dump diagnostic and abort.
3112 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003113 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003114 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3115 }
3116 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003117 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003118}
3119
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003120void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003121 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003122 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003123 mirror::DexCache* dex_cache = GetDexCache(i);
3124 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003125 }
3126}
3127
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003128mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003129 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003130 if (UNLIKELY(klass == nullptr)) {
3131 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003132 }
3133 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003134}
3135
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003136mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3137 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003138 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003139 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003140 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003141 StackHandleScope<1> hs(self);
3142 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003143 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003144 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003145 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003146 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3147 const char* descriptor = Primitive::Descriptor(type);
3148 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003149 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003150 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003151}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003152
Brian Carlstrombe977852011-07-19 14:54:54 -07003153// Create an array class (i.e. the class object for the array, not the
3154// array itself). "descriptor" looks like "[C" or "[[[[B" or
3155// "[Ljava/lang/String;".
3156//
3157// If "descriptor" refers to an array of primitives, look up the
3158// primitive type's internally-generated class object.
3159//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003160// "class_loader" is the class loader of the class that's referring to
3161// us. It's used to ensure that we're looking for the element type in
3162// the right context. It does NOT become the class loader for the
3163// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003164//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003165// Returns nullptr with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08003166mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003167 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003168 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003169 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003170 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003171 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3172 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003173 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003174 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003175 // We need to accept erroneous classes as component types.
Ian Rogers7b078e82014-09-10 14:44:24 -07003176 component_type.Assign(LookupClass(self, descriptor + 1, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003177 if (component_type.Get() == nullptr) {
3178 DCHECK(self->IsExceptionPending());
3179 return nullptr;
3180 } else {
3181 self->ClearException();
3182 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003183 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003184 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3185 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3186 return nullptr;
3187 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003188 // See if the component type is already loaded. Array classes are
3189 // always associated with the class loader of their underlying
3190 // element type -- an array of Strings goes with the loader for
3191 // java/lang/String -- so we need to look for it there. (The
3192 // caller should have checked for the existence of the class
3193 // before calling here, but they did so with *their* class loader,
3194 // not the component type's loader.)
3195 //
3196 // If we find it, the caller adds "loader" to the class' initiating
3197 // loader list, which should prevent us from going through this again.
3198 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003199 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003200 // are the same, because our caller (FindClass) just did the
3201 // lookup. (Even if we get this wrong we still have correct behavior,
3202 // because we effectively do this lookup again when we add the new
3203 // class to the hash table --- necessary because of possible races with
3204 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003205 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003206 mirror::Class* new_class = LookupClass(self, descriptor, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003207 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003208 return new_class;
3209 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003210 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003211
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003212 // Fill out the fields in the Class.
3213 //
3214 // It is possible to execute some methods against arrays, because
3215 // all arrays are subclasses of java_lang_Object_, so we need to set
3216 // up a vtable. We can just point at the one in java_lang_Object_.
3217 //
3218 // Array classes are simple enough that we don't need to do a full
3219 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003220 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003221 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003222 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003223 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003224 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003225 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003226 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003227 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003228 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003229 } else if (strcmp(descriptor,
3230 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003231 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003232 } else if (strcmp(descriptor,
3233 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003234 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003235 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003236 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003237 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003238 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003239 }
3240 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003241 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003242 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003243 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003244 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003245 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003246 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003247 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003248 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003249 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003250 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003251 new_class->SetSuperClass(java_lang_Object);
3252 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003253 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003254 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003255 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
3256 new_class->PopulateEmbeddedImtAndVTable();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003257 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003258 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003259 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003260
3261
3262 // All arrays have java/lang/Cloneable and java/io/Serializable as
3263 // interfaces. We need to set that up here, so that stuff like
3264 // "instanceof" works right.
3265 //
3266 // Note: The GC could run during the call to FindSystemClass,
3267 // so we need to make sure the class object is GC-valid while we're in
3268 // there. Do this by clearing the interface list so the GC will just
3269 // think that the entries are null.
3270
3271
3272 // Use the single, global copies of "interfaces" and "iftable"
3273 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003274 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003275 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003276 CHECK(array_iftable != nullptr);
3277 new_class->SetIfTable(array_iftable);
3278 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003279
Elliott Hughes00626c22013-06-14 15:04:14 -07003280 // Inherit access flags from the component type.
3281 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3282 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3283 access_flags &= kAccJavaFlagsMask;
3284 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003285 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003286 access_flags |= kAccAbstract | kAccFinal;
3287 access_flags &= ~kAccInterface;
3288
3289 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003290
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003291 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003292 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003293 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003294 }
3295 // Another thread must have loaded the class after we
3296 // started but before we finished. Abandon what we've
3297 // done.
3298 //
3299 // (Yes, this happens.)
3300
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003301 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003302}
3303
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003304mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003305 switch (type) {
3306 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003307 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003308 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003309 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003310 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003311 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003312 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003313 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003314 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003315 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003316 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003317 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003318 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003319 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003320 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003321 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003322 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003323 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003324 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003325 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003326 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003327 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003328 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003329 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003330}
3331
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003332mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3333 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003334 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003335 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003336 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003337 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003338 source += " from ";
3339 source += dex_cache->GetLocation()->ToModifiedUtf8();
3340 }
3341 LOG(INFO) << "Loaded class " << descriptor << source;
3342 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003343 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003344 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003345 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003346 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003347 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003348 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003349 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003350 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003351 // Check a class loaded with the system class loader matches one in the image if the class
3352 // is in the image.
3353 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003354 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003355 CHECK(klass == existing);
3356 }
3357 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003358 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003359 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003360 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003361 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003362 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003363 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003364}
3365
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003366mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3367 size_t hash) {
3368 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3369 mirror::Class* existing =
3370 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3371
3372 if (existing == nullptr) {
3373 CHECK(klass->IsProxyClass());
3374 return nullptr;
3375 }
3376
3377 CHECK_NE(existing, klass) << descriptor;
3378 CHECK(!existing->IsResolved()) << descriptor;
3379 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3380
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003381 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3382 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003383 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07003384 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003385 class_table_.erase(it);
3386 break;
3387 }
3388 }
3389
3390 CHECK(!klass->IsTemp()) << descriptor;
3391 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3392 dex_cache_image_class_lookup_required_) {
3393 // Check a class loaded with the system class loader matches one in the image if the class
3394 // is in the image.
3395 existing = LookupClassFromImage(descriptor);
3396 if (existing != nullptr) {
3397 CHECK(klass == existing) << descriptor;
3398 }
3399 }
3400 VerifyObject(klass);
3401
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003402 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003403 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003404 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003405 }
3406
3407 return existing;
3408}
3409
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003410bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003411 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003412 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07003413 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3414 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003415 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003416 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003417 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003418 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08003419 return true;
3420 }
3421 }
3422 return false;
3423}
3424
Ian Rogers7b078e82014-09-10 14:44:24 -07003425mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003426 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003427 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003428 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003429 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003430 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003431 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003432 return result;
3433 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003434 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003435 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3436 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003437 } else {
3438 // Lookup failed but need to search dex_caches_.
3439 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003440 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003441 InsertClass(descriptor, result, hash);
3442 } else {
3443 // Searching the image dex files/caches failed, we don't want to get into this situation
3444 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3445 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003446 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003447 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3448 MoveImageClassesToClassTable();
3449 }
3450 }
3451 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003452 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003453}
3454
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003455mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3456 const mirror::ClassLoader* class_loader,
3457 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003458 auto end = class_table_.end();
3459 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003460 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003461 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003462 if (kIsDebugBuild) {
3463 // Check for duplicates in the table.
3464 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003465 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003466 CHECK(!(klass2->GetClassLoader() == class_loader &&
3467 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003468 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3469 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003470 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003471 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003472 return klass;
3473 }
3474 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003475 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003476}
3477
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003478static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3479 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3480 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003481 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003482 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3483 return root->AsObjectArray<mirror::DexCache>();
3484}
3485
3486void ClassLinker::MoveImageClassesToClassTable() {
3487 Thread* self = Thread::Current();
3488 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3489 if (!dex_cache_image_class_lookup_required_) {
3490 return; // All dex cache classes are already in the class table.
3491 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003492 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003493 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003494 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003495 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3496 mirror::DexCache* dex_cache = dex_caches->Get(i);
3497 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3498 for (int32_t j = 0; j < types->GetLength(); j++) {
3499 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003500 if (klass != nullptr) {
3501 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003502 const char* descriptor = klass->GetDescriptor(&temp);
3503 size_t hash = Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003504 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3505 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003506 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3507 << PrettyClassAndClassLoader(klass);
3508 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003509 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003510 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003511 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003512 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003513 }
3514 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003515 }
3516 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003517 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003518}
3519
3520mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003521 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003522 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3523 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3524 mirror::DexCache* dex_cache = dex_caches->Get(i);
3525 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003526 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003527 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003528 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003529 const DexFile::TypeId* type_id =
3530 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003531 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003532 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3533 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003534 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003535 return klass;
3536 }
3537 }
3538 }
3539 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003540 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003541}
3542
3543void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3544 result.clear();
3545 if (dex_cache_image_class_lookup_required_) {
3546 MoveImageClassesToClassTable();
3547 }
3548 size_t hash = Hash(descriptor);
3549 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003550 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003551 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003552 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003553 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003554 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003555 }
3556 }
3557}
3558
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003559void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003560 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003561 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003562
Ian Rogers9ffb0392012-09-10 11:56:50 -07003563 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003564 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003565 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003566 return;
3567 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003568 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3569 return;
3570 }
jeffhao98eacac2011-09-14 16:11:53 -07003571
Ian Rogers9ffb0392012-09-10 11:56:50 -07003572 // The class might already be erroneous, for example at compile time if we attempted to verify
3573 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003574 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003575 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003576 return;
3577 }
3578
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003579 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003580 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003581 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003582 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003583 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003584 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003585 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003586 }
jeffhao98eacac2011-09-14 16:11:53 -07003587
Jeff Hao4a200f52014-04-01 14:58:49 -07003588 // Skip verification if disabled.
3589 if (!Runtime::Current()->IsVerificationEnabled()) {
3590 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003591 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003592 return;
3593 }
3594
Ian Rogers9ffb0392012-09-10 11:56:50 -07003595 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003596 StackHandleScope<2> hs(self);
3597 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003598 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003599 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003600 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003601
3602 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003603 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003604 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003605 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003606 std::string error_msg(
3607 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3608 PrettyDescriptor(klass.Get()).c_str(),
3609 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003610 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003611 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3612 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003613 self->ClearException();
3614 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003615 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3616 if (cause.Get() != nullptr) {
3617 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003618 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003619 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003620 if (Runtime::Current()->IsCompiler()) {
3621 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3622 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003623 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003624 return;
3625 }
3626 }
3627
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003628 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003629 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003630 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003631 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003632 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003633 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003634 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003635 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003636 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3637 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003638 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003639 return;
3640 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003641 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003642 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003643 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003644 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003645 Runtime::Current()->IsCompiler(),
3646 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003647 }
3648 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003649 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003650 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003651 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3652 << " because: " << error_msg;
3653 }
Ian Rogers1f539342012-10-03 21:09:42 -07003654 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003655 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003656 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003657 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003658 // Even though there were no verifier failures we need to respect whether the super-class
3659 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003660 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003661 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003662 } else {
3663 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003664 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003665 // Pretend a soft failure occured so that we don't consider the class verified below.
3666 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003667 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003668 } else {
3669 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3670 // Soft failures at compile time should be retried at runtime. Soft
3671 // failures at runtime will be handled by slow paths in the generated
3672 // code. Set status accordingly.
3673 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003674 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003675 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003676 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003677 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3678 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003679 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003680 }
3681 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003682 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003683 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003684 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3685 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003686 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003687 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003688 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003689 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003690 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003691 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003692 // Let the interpreter know it by setting the kAccPreverified flag onto each
3693 // method.
3694 // Note: we're going here during compilation and at runtime. When we set the
3695 // kAccPreverified flag when compiling image classes, the flag is recorded
3696 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003697 EnsurePreverifiedMethods(klass);
3698 }
3699}
3700
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003701void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003702 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003703 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003704 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003705 }
jeffhao98eacac2011-09-14 16:11:53 -07003706}
3707
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003708bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3709 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003710 // If we're compiling, we can only verify the class using the oat file if
3711 // we are not compiling the image or if the class we're verifying is not part of
3712 // the app. In other words, we will only check for preverification of bootclasspath
3713 // classes.
3714 if (Runtime::Current()->IsCompiler()) {
3715 // Are we compiling the bootclasspath?
3716 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3717 return false;
3718 }
3719 // We are compiling an app (not the image).
3720
3721 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003722 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003723 return false;
3724 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003725 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003726
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003727 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003728 // In case we run without an image there won't be a backing oat file.
3729 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003730 return false;
3731 }
3732
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003733 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003734 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003735 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3736 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003737 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003738 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003739 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003740 // Compile time verification failed with a soft error. Compile time verification can fail
3741 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003742 // class ... {
3743 // Foo x;
3744 // .... () {
3745 // if (...) {
3746 // v1 gets assigned a type of resolved class Foo
3747 // } else {
3748 // v1 gets assigned a type of unresolved class Bar
3749 // }
3750 // iput x = v1
3751 // } }
3752 // when we merge v1 following the if-the-else it results in Conflict
3753 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3754 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3755 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3756 // at compile time).
3757 return false;
3758 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003759 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003760 // Compile time verification failed with a hard error. This is caused by invalid instructions
3761 // in the class. These errors are unrecoverable.
3762 return false;
3763 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003764 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003765 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3766 // not loading the class.
3767 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3768 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003769 return false;
3770 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003771 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003772 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003773 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003774 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003775
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003776 return false;
3777}
3778
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003779void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003780 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003781 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3782 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3783 }
3784 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3785 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3786 }
3787}
3788
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003789void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003790 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003791 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3792 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003793 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003794 return; // native or abstract method
3795 }
3796 if (code_item->tries_size_ == 0) {
3797 return; // nothing to process
3798 }
Ian Rogers13735952014-10-08 12:43:28 -07003799 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003800 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3801 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3802 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3803 CatchHandlerIterator iterator(handlers_ptr);
3804 for (; iterator.HasNext(); iterator.Next()) {
3805 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3806 // unresolved exception types will be ignored by exception delivery
3807 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003808 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003809 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003810 DCHECK(Thread::Current()->IsExceptionPending());
3811 Thread::Current()->ClearException();
3812 }
3813 }
3814 }
3815 handlers_ptr = iterator.EndDataPointer();
3816 }
3817}
3818
Brian Carlstromea46f952013-07-30 01:26:50 -07003819static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003820static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3821 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003822
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003823mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003824 jobjectArray interfaces, jobject loader,
3825 jobjectArray methods, jobjectArray throws) {
3826 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003827 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003828 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003829 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003830 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003831 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003832 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003833 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003834 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003835 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003836 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3837 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003838 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003839 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003840 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003841 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003842 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003843 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003844
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003845 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003846 {
3847 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003848 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003849 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003850 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003851 }
3852 klass->SetSFields(sfields);
3853 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003854 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3855 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003856 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3857 if (UNLIKELY(interfaces_sfield.Get() == 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 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003861 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003862 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003863 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003864 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3865 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003866 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3867 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003868 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003869 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003870 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003871 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003872 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003873 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003874 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003875
Ian Rogers466bb252011-10-14 03:29:56 -07003876 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003877 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003878 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003879 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003880 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003881 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003882 }
3883 klass->SetDirectMethods(directs);
3884 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003885 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003886 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003887 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003888 }
3889 klass->SetDirectMethod(0, constructor);
3890 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003891
Mathieu Chartier590fee92013-09-13 13:46:47 -07003892 // Create virtual method using specified prototypes.
3893 size_t num_virtual_methods =
3894 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003895 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003896 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3897 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003898 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003899 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003900 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003901 }
3902 klass->SetVirtualMethods(virtuals);
3903 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003904 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003905 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003906 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3907 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003908 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003909 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003910 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003911 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003912 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003913 }
3914 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003915 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003916
3917 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003918 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003919 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003920
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003921 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3922 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003923 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003924 // Must hold lock on object when resolved.
3925 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003926 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003927 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003928 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003929 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003930 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003931 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003932 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003933 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003934
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003935 CHECK(klass->IsRetired());
3936 CHECK_NE(klass.Get(), new_class);
3937 klass.Assign(new_class);
3938
3939 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003940 interfaces_sfield->SetObject<false>(klass.Get(),
3941 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003942 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003943 throws_sfield->SetObject<false>(klass.Get(),
3944 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003945
3946 {
3947 // Lock on klass is released. Lock new class object.
3948 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003949 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003950 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003951
3952 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003953 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003954 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003955 CheckProxyConstructor(klass->GetDirectMethod(0));
3956 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003957 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003958 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3959 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003960 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003961 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3962 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003963 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003964
Mathieu Chartier590fee92013-09-13 13:46:47 -07003965 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003966 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003967 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003968 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3969
3970 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003971 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003972 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003973
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003974 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003975 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003976 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003977 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003978 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003979 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003980 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003981 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003982}
3983
Ian Rogersef7d42f2014-01-06 12:55:46 -08003984std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003985 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003986 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003987 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003988 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3989}
3990
Ian Rogersef7d42f2014-01-06 12:55:46 -08003991mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3992 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003993 DCHECK(proxy_class->IsProxyClass());
3994 DCHECK(proxy_method->IsProxyMethod());
3995 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003996 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003997 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003998 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003999 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004000 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07004001 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004002 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08004003 break;
4004 }
4005 }
4006 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07004007 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08004008 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07004009 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07004010 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08004011 return resolved_method;
4012}
4013
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004014
Brian Carlstromea46f952013-07-30 01:26:50 -07004015mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004016 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07004017 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07004018 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07004019 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004020 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07004021 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
4022 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02004023 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4024 // constructor method.
4025 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
4026 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07004027 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4028 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07004029 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
4030 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004031 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07004032 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004033 }
Ian Rogers466bb252011-10-14 03:29:56 -07004034 // Make this constructor public and fix the class to be our Proxy version
4035 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004036 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004037 return constructor;
4038}
4039
Brian Carlstromea46f952013-07-30 01:26:50 -07004040static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004041 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004042 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004043 CHECK_STREQ(constructor->GetName(), "<init>");
4044 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4045 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004046 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004047}
4048
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004049mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004050 Handle<mirror::Class> klass,
4051 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004052 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4053 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004054 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004055 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004056 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004057 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004058 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004059 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004060 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004061 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004062 }
Ian Rogers466bb252011-10-14 03:29:56 -07004063
4064 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4065 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004066 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004067 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004068
Ian Rogers466bb252011-10-14 03:29:56 -07004069 // At runtime the method looks like a reference and argument saving method, clone the code
4070 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004071 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4072 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004073 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004074
Ian Rogersc2b44472011-12-14 21:17:17 -08004075 return method;
4076}
Jesse Wilson95caa792011-10-12 18:14:17 -04004077
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004078static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4079 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004080 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004081 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004082 CHECK(!prototype->IsFinal());
4083 CHECK(method->IsFinal());
4084 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004085
4086 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4087 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4088 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004089 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4090 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004091 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4092
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004093 StackHandleScope<2> hs(Thread::Current());
4094 MethodHelper mh(hs.NewHandle(method.Get()));
4095 MethodHelper mh2(hs.NewHandle(prototype.Get()));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004096 CHECK_STREQ(method->GetName(), prototype->GetName());
4097 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004098 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08004099 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004100}
4101
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004102static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4103 bool can_init_parents)
4104 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004105 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004106 return true;
4107 }
4108 if (!can_init_statics) {
4109 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004110 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004111 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004112 return false;
4113 }
4114 // Check if there are encoded static values needing initialization.
4115 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004116 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004117 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004118 if (dex_class_def->static_values_off_ != 0) {
4119 return false;
4120 }
4121 }
4122 }
4123 if (!klass->IsInterface() && klass->HasSuperClass()) {
4124 mirror::Class* super_class = klass->GetSuperClass();
4125 if (!can_init_parents && !super_class->IsInitialized()) {
4126 return false;
4127 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004128 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004129 return false;
4130 }
4131 }
4132 }
4133 return true;
4134}
4135
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004136bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004137 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004138 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4139
4140 // Are we already initialized and therefore done?
4141 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4142 // an initialized class will never change its state.
4143 if (klass->IsInitialized()) {
4144 return true;
4145 }
4146
4147 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004148 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004149 return false;
4150 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004151
Ian Rogers7b078e82014-09-10 14:44:24 -07004152 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004153 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004154 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004155 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004156
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004157 // Re-check under the lock in case another thread initialized ahead of us.
4158 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004159 return true;
4160 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004161
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004162 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004163 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004164 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004165 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004166 return false;
4167 }
4168
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004169 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004170
4171 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004172 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004173 if (!klass->IsVerified()) {
4174 // We failed to verify, expect either the klass to be erroneous or verification failed at
4175 // compile time.
4176 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004177 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004178 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004179 } else {
4180 CHECK(Runtime::Current()->IsCompiler());
4181 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004182 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004183 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004184 } else {
4185 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004186 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004187 }
4188
Brian Carlstromd1422f82011-09-28 11:37:09 -07004189 // If the class is kStatusInitializing, either this thread is
4190 // initializing higher up the stack or another thread has beat us
4191 // to initializing and we need to wait. Either way, this
4192 // invocation of InitializeClass will not be responsible for
4193 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004194 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004195 // Could have got an exception during verification.
4196 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004197 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004198 return false;
4199 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004200 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004201 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004202 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004203 return true;
4204 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004205 // No. That's fine. Wait for another thread to finish initializing.
4206 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004207 }
4208
4209 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004210 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004211 return false;
4212 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004213 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004214
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004215 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004216
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004217 // From here out other threads may observe that we're initializing and so changes of state
4218 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004219 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004220 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004221
4222 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004223 }
4224
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004225 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004226 if (!klass->IsInterface() && klass->HasSuperClass()) {
4227 mirror::Class* super_class = klass->GetSuperClass();
4228 if (!super_class->IsInitialized()) {
4229 CHECK(!super_class->IsInterface());
4230 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004231 StackHandleScope<1> hs(self);
4232 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004233 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004234 if (!super_initialized) {
4235 // The super class was verified ahead of entering initializing, we should only be here if
4236 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004237 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004238 << "Super class initialization failed for "
4239 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004240 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004241 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004242 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004243 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004244 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004245 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004246 return false;
4247 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004248 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004249 }
4250
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004251 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004252 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004253 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004254 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004255 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004256 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004257 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004258 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4259 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004260 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004261 ClassDataItemIterator field_it(dex_file, class_data);
4262 if (value_it.HasNext()) {
4263 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004264 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004265 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004266 StackHandleScope<1> hs(self);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004267 Handle<mirror::ArtField> field(hs.NewHandle(
4268 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004269 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004270 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004271 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004272 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004273 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004274 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004275 }
4276 }
4277 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004278
Ian Rogersd91d6d62013-09-25 20:26:14 -07004279 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004280 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004281 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004282 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004283 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004284 }
4285
Ian Rogers7b078e82014-09-10 14:44:24 -07004286 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004287 uint64_t t1 = NanoTime();
4288
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004289 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004290 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004291 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004292
4293 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004294 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004295 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004296 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004297 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004298 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4299 RuntimeStats* thread_stats = self->GetStats();
4300 ++global_stats->class_init_count;
4301 ++thread_stats->class_init_count;
4302 global_stats->class_init_time_ns += (t1 - t0);
4303 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004304 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004305 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004306 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004307 std::string temp;
4308 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004309 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004310 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004311 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004312 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004313 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004314 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004315 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004316}
4317
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004318bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004319 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004320 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004321 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004322 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004323 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004324 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004325
4326 // When we wake up, repeat the test for init-in-progress. If
4327 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004328 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004329 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004330 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004331 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004332 return false;
4333 }
4334 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004335 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004336 continue;
4337 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004338 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004339 // Compile time initialization failed.
4340 return false;
4341 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004342 if (klass->IsErroneous()) {
4343 // The caller wants an exception, but it was thrown in a
4344 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004345 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004346 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004347 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004348 return false;
4349 }
4350 if (klass->IsInitialized()) {
4351 return true;
4352 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004353 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004354 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004355 }
Ian Rogers07140832014-09-30 15:43:59 -07004356 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004357}
4358
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004359bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004360 if (klass->IsInterface()) {
4361 return true;
4362 }
Ian Rogers151f2212014-05-06 11:27:27 -07004363 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004364 StackHandleScope<2> hs(Thread::Current());
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004365 MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4366 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004367 if (klass->HasSuperClass() &&
4368 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004369 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4370 mh.ChangeMethod(klass->GetVTableEntry(i));
4371 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004372 if (mh.GetMethod() != super_mh.GetMethod() &&
4373 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4374 ThrowLinkageError(klass.Get(),
4375 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004376 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004377 PrettyMethod(mh.GetMethod()).c_str(),
4378 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004379 return false;
4380 }
4381 }
4382 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004383 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004384 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4385 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4386 for (uint32_t j = 0; j < num_methods; ++j) {
4387 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4388 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004389 if (mh.GetMethod() != super_mh.GetMethod() &&
4390 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4391 ThrowLinkageError(klass.Get(),
4392 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004393 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004394 PrettyMethod(mh.GetMethod()).c_str(),
4395 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004396 return false;
4397 }
4398 }
4399 }
4400 }
4401 return true;
4402}
4403
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004404bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4405 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004406 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004407 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004408 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004409 return true;
4410 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004411 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004412 if (!success) {
4413 if (can_init_fields && can_init_parents) {
4414 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4415 }
4416 } else {
4417 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004418 }
4419 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004420}
4421
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004422void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4423 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
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 fields = new_class->GetSFields();
4433 if (fields != nullptr) {
4434 for (int index = 0; index < fields->GetLength(); index ++) {
4435 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4436 fields->Get(index)->SetDeclaringClass(new_class);
4437 }
4438 }
4439 }
4440
4441 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
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 methods = new_class->GetVirtualMethods();
4451 if (methods != nullptr) {
4452 for (int index = 0; index < methods->GetLength(); index ++) {
4453 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4454 methods->Get(index)->SetDeclaringClass(new_class);
4455 }
4456 }
4457 }
4458}
4459
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004460bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4461 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004462 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004463 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004464
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004465 if (!LinkSuperClass(klass)) {
4466 return false;
4467 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004468 if (!LinkMethods(self, klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004469 return false;
4470 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004471 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004472 return false;
4473 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004474 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004475 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004476 return false;
4477 }
4478 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004479 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004480
4481 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4482 // We don't need to retire this class as it has no embedded tables or it was created the
4483 // correct size during class linker initialization.
4484 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4485
4486 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4487 klass->PopulateEmbeddedImtAndVTable();
4488 }
4489
4490 // This will notify waiters on klass that saw the not yet resolved
4491 // class in the class_table_ during EnsureResolved.
4492 klass->SetStatus(mirror::Class::kStatusResolved, self);
4493 *new_class = klass.Get();
4494 } else {
4495 CHECK(!klass->IsResolved());
4496 // Retire the temporary class and create the correctly sized resolved class.
4497 *new_class = klass->CopyOf(self, class_size);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004498 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004499 CHECK(self->IsExceptionPending()); // Expect an OOME.
4500 klass->SetStatus(mirror::Class::kStatusError, self);
4501 return false;
4502 }
4503
4504 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4505 StackHandleScope<1> hs(self);
4506 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4507 ObjectLock<mirror::Class> lock(self, new_class_h);
4508
4509 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4510
4511 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004512 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004513
4514 // This will notify waiters on temp class that saw the not yet resolved class in the
4515 // class_table_ during EnsureResolved.
4516 klass->SetStatus(mirror::Class::kStatusRetired, self);
4517
4518 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4519 // This will notify waiters on new_class that saw the not yet resolved
4520 // class in the class_table_ during EnsureResolved.
4521 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004522 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004523 return true;
4524}
4525
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004526bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004527 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004528 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4529 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004530 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004531 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004532 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004533 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004534 return false;
4535 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004536 // Verify
4537 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004538 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004539 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004540 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004541 return false;
4542 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004543 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004544 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004545 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004546 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004547 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004548 for (size_t i = 0; i < interfaces->Size(); i++) {
4549 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004550 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004551 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004552 DCHECK(Thread::Current()->IsExceptionPending());
4553 return false;
4554 }
4555 // Verify
4556 if (!klass->CanAccess(interface)) {
4557 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004558 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004559 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004560 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004561 return false;
4562 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004563 }
4564 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004565 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004566 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004567 return true;
4568}
4569
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004570bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004571 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004572 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004573 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004574 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004575 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004576 return false;
4577 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004578 return true;
4579 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004580 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004581 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4582 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004583 return false;
4584 }
4585 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004586 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004587 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004588 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004589 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004590 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004591 return false;
4592 }
4593 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004594 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004595 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004596 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004597 return false;
4598 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004599
Brian Carlstromf3632832014-05-20 15:36:53 -07004600 // Inherit kAccClassIsFinalizable from the superclass in case this
4601 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004602 if (super->IsFinalizable()) {
4603 klass->SetFinalizable();
4604 }
4605
Elliott Hughes2da50362011-10-10 16:57:08 -07004606 // Inherit reference flags (if any) from the superclass.
4607 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4608 if (reference_flags != 0) {
4609 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4610 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004611 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004612 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004613 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004614 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004615 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004616 return false;
4617 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004618
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004619 if (kIsDebugBuild) {
4620 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004621 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004622 CHECK(super->IsResolved());
4623 super = super->GetSuperClass();
4624 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004625 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004626 return true;
4627}
4628
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004629// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004630bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
4631 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004632 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004633 if (klass->IsInterface()) {
4634 // No vtable.
4635 size_t count = klass->NumVirtualMethods();
4636 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004637 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004638 return false;
4639 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004640 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004641 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004642 }
jeffhaobdb76512011-09-07 11:43:16 -07004643 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004644 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004645 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07004646 // Link virtual and interface method tables
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004647 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004648 }
4649 return true;
4650}
4651
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004652bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004653 if (klass->HasSuperClass()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004654 uint32_t max_count = klass->NumVirtualMethods() +
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004655 klass->GetSuperClass()->GetVTableLength();
4656 size_t actual_count = klass->GetSuperClass()->GetVTableLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004657 CHECK_LE(actual_count, max_count);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004658 StackHandleScope<4> hs(self);
4659 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004660 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004661 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4662 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4663 if (UNLIKELY(vtable.Get() == nullptr)) {
4664 CHECK(self->IsExceptionPending()); // OOME.
4665 return false;
4666 }
4667 int len = super_class->GetVTableLength();
Mingyao Yang1a128582014-07-22 17:33:25 -07004668 for (int i = 0; i < len; i++) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004669 vtable->Set<false>(i, super_class->GetVTableEntry(i));
4670 }
4671 } else {
Mingyao Yang38eecb02014-08-13 14:51:03 -07004672 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004673 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4674 if (UNLIKELY(vtable.Get() == nullptr)) {
4675 CHECK(self->IsExceptionPending()); // OOME.
4676 return false;
4677 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004678 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004679
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004680 // See if any of our virtual methods override the superclass.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004681 MutableMethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4682 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004683 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004684 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004685 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004686 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004687 for (; j < actual_count; ++j) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004688 mirror::ArtMethod* super_method = vtable->Get(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004689 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004690 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004691 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4692 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004693 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004694 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004695 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004696 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004697 return false;
4698 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004699 vtable->Set<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004700 local_method->SetMethodIndex(j);
4701 break;
4702 } else {
4703 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4704 << " would have incorrectly overridden the package-private method in "
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004705 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004706 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004707 }
4708 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004709 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004710 // Not overriding, append.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004711 vtable->Set<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004712 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004713 actual_count += 1;
4714 }
4715 }
4716 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004717 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004718 return false;
4719 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004720 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004721 CHECK_LE(actual_count, max_count);
4722 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004723 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004724 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004725 CHECK(self->IsExceptionPending()); // OOME.
4726 return false;
4727 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004728 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004729 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004730 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004731 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004732 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004733 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004734 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004735 return false;
4736 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004737 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004738 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004739 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004740 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004741 CHECK(self->IsExceptionPending()); // OOME.
4742 return false;
4743 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004744 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004745 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004746 vtable->Set<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004747 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004748 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004749 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004750 }
4751 return true;
4752}
4753
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004754bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass,
4755 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004756 Thread* const self = Thread::Current();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004757 Runtime* const runtime = Runtime::Current();
Jeff Hao88474b42013-10-23 16:24:40 -07004758 // Set the imt table to be all conflicts by default.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004759 klass->SetImTable(runtime->GetDefaultImt());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004760 size_t super_ifcount;
4761 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004762 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004763 } else {
4764 super_ifcount = 0;
4765 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07004766 uint32_t num_interfaces =
4767 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4768 size_t ifcount = super_ifcount + num_interfaces;
4769 for (size_t i = 0; i < num_interfaces; i++) {
4770 mirror::Class* interface =
4771 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4772 interfaces->Get(i);
4773 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004774 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004775 if (ifcount == 0) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004776 // Class implements no interfaces.
4777 DCHECK_EQ(klass->GetIfTableCount(), 0);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004778 DCHECK(klass->GetIfTable() == nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004779 return true;
4780 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004781 if (ifcount == super_ifcount) {
4782 // Class implements same interfaces as parent, are any of these not marker interfaces?
4783 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004784 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Ian Rogers9bc81912012-10-11 21:43:36 -07004785 for (size_t i = 0; i < ifcount; ++i) {
4786 if (super_iftable->GetMethodArrayCount(i) > 0) {
4787 has_non_marker_interface = true;
4788 break;
4789 }
4790 }
4791 if (!has_non_marker_interface) {
4792 // Class just inherits marker interfaces from parent so recycle parent's iftable.
4793 klass->SetIfTable(super_iftable);
4794 return true;
4795 }
4796 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004797 StackHandleScope<5> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004798 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004799 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004800 CHECK(self->IsExceptionPending()); // OOME.
4801 return false;
4802 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004803 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004804 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004805 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004806 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004807 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004808 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004809 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004810 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004811 // Flatten the interface inheritance hierarchy.
4812 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004813 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004814 mirror::Class* interface =
Mathieu Chartierf8322842014-05-16 10:59:25 -07004815 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4816 interfaces->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004817 DCHECK(interface != nullptr);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004818 if (!interface->IsInterface()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004819 std::string temp;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004820 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4821 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers1ff3c982014-08-12 02:30:58 -07004822 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004823 return false;
4824 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004825 // Check if interface is already in iftable
4826 bool duplicate = false;
4827 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004828 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004829 if (existing_interface == interface) {
4830 duplicate = true;
4831 break;
4832 }
4833 }
4834 if (!duplicate) {
4835 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004836 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004837 // Add this interface's non-duplicate super-interfaces.
4838 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004839 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004840 bool super_duplicate = false;
4841 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004842 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004843 if (existing_interface == super_interface) {
4844 super_duplicate = true;
4845 break;
4846 }
4847 }
4848 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004849 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004850 }
4851 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004852 }
4853 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004854 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004855 // Shrink iftable in case duplicates were found
4856 if (idx < ifcount) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004857 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004858 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004859 CHECK(self->IsExceptionPending()); // OOME.
4860 return false;
4861 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004862 ifcount = idx;
4863 } else {
4864 CHECK_EQ(idx, ifcount);
4865 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004866 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004867
4868 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004869 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004870 return true;
4871 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004872 self->AllowThreadSuspension();
Jeff Hao88474b42013-10-23 16:24:40 -07004873 // Allocate imtable
4874 bool imtable_changed = false;
Ian Rogers700a4022014-05-19 16:49:03 -07004875 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004876 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004877 if (UNLIKELY(imtable.Get() == nullptr)) {
Jeff Hao88474b42013-10-23 16:24:40 -07004878 CHECK(self->IsExceptionPending()); // OOME.
4879 return false;
4880 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004881 MutableMethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4882 MutableMethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004883 size_t max_miranda_methods = 0; // The max size of miranda_list.
4884 for (size_t i = 0; i < ifcount; ++i) {
4885 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4886 }
4887 Handle<mirror::ObjectArray<mirror::ArtMethod>>
4888 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
4889 size_t miranda_list_size = 0; // The current size of miranda_list.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004890 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004891 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004892 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004893 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004894 StackHandleScope<2> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004895 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004896 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4897 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004898 CHECK(self->IsExceptionPending()); // OOME.
4899 return false;
4900 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004901 iftable->SetMethodArray(i, method_array.Get());
Ian Rogers700a4022014-05-19 16:49:03 -07004902 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004903 hs.NewHandle(klass->GetVTableDuringLinking()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004904 for (size_t j = 0; j < num_methods; ++j) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004905 interface_mh.ChangeMethod(iftable->GetInterface(i)->GetVirtualMethod(j));
Ian Rogers9bc81912012-10-11 21:43:36 -07004906 int32_t k;
4907 // For each method listed in the interface's method list, find the
4908 // matching method in our class's method list. We want to favor the
4909 // subclass over the superclass, which just requires walking
4910 // back from the end of the vtable. (This only matters if the
4911 // superclass defines a private method and this class redefines
4912 // it -- otherwise it would use the same vtable slot. In .dex files
4913 // those don't end up in the virtual method table, so it shouldn't
4914 // matter which direction we go. We walk it backward anyway.)
4915 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004916 vtable_mh.ChangeMethod(vtable->Get(k));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004917 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004918 if (!vtable_mh.Get()->IsAbstract() && !vtable_mh.Get()->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004919 ThrowIllegalAccessError(
4920 klass.Get(),
4921 "Method '%s' implementing interface method '%s' is not public",
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004922 PrettyMethod(vtable_mh.Get()).c_str(),
4923 PrettyMethod(interface_mh.Get()).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004924 return false;
4925 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004926 method_array->Set<false>(j, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004927 // Place method in imt if entry is empty, place conflict otherwise.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004928 uint32_t imt_index = interface_mh.Get()->GetDexMethodIndex() % mirror::Class::kImtSize;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004929 if (imtable->Get(imt_index) == nullptr) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004930 imtable->Set<false>(imt_index, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004931 imtable_changed = true;
4932 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004933 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -07004934 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004935 break;
4936 }
4937 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004938 if (k < 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004939 StackHandleScope<1> hs(self);
4940 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004941 for (size_t l = 0; l < miranda_list_size; ++l) {
4942 mirror::ArtMethod* mir_method = miranda_list->Get(l);
4943 DCHECK(mir_method != nullptr);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004944 vtable_mh.ChangeMethod(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004945 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004946 miranda_method.Assign(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004947 break;
4948 }
4949 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004950 if (miranda_method.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004951 // Point the interface table at a phantom slot.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004952 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_mh.Get()->Clone(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004953 if (UNLIKELY(miranda_method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004954 CHECK(self->IsExceptionPending()); // OOME.
4955 return false;
4956 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004957 DCHECK_LT(miranda_list_size, max_miranda_methods);
4958 miranda_list->Set<false>(miranda_list_size++, miranda_method.Get());
Ian Rogers9bc81912012-10-11 21:43:36 -07004959 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004960 method_array->Set<false>(j, miranda_method.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004961 }
4962 }
4963 }
4964 }
Jeff Hao88474b42013-10-23 16:24:40 -07004965 if (imtable_changed) {
4966 // Fill in empty entries in interface method table with conflict.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004967 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004968 for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004969 if (imtable->Get(i) == nullptr) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004970 imtable->Set<false>(i, imt_conflict_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004971 }
4972 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004973 klass->SetImTable(imtable.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004974 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004975 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004976 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004977 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004978 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4979 if (old_method_count == 0) {
4980 virtuals = AllocArtMethodArray(self, new_method_count);
4981 } else {
4982 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4983 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004984 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004985 CHECK(self->IsExceptionPending()); // OOME.
4986 return false;
4987 }
4988 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004989
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004990 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004991 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004992 hs.NewHandle(klass->GetVTableDuringLinking()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004993 CHECK(vtable.Get() != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004994 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004995 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004996 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004997 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004998 CHECK(self->IsExceptionPending()); // OOME.
4999 return false;
5000 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005001 for (size_t i = 0; i < miranda_list_size; ++i) {
5002 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005003 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005004 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5005 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5006 klass->SetVirtualMethod(old_method_count + i, method);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005007 vtable->Set<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005008 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005009 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005010 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005011 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005012
Brian Carlstromea46f952013-07-30 01:26:50 -07005013 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07005014 for (int i = 0; i < vtable->GetLength(); ++i) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005015 CHECK(vtable->Get(i) != nullptr);
Elliott Hughes4681c802011-09-25 18:04:37 -07005016 }
5017
Ian Rogers7b078e82014-09-10 14:44:24 -07005018 self->AllowThreadSuspension();
Elliott Hughes4681c802011-09-25 18:04:37 -07005019
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005020 return true;
5021}
5022
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005023bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005024 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005025 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005026}
5027
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005028bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005029 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005030 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005031}
5032
Brian Carlstromdbc05252011-09-09 01:59:59 -07005033struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005034 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5035 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005036 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005037 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005038 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005039 // 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 -07005040 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5041 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005042 if (type1 != type2) {
5043 bool is_primitive1 = type1 != Primitive::kPrimNot;
5044 bool is_primitive2 = type2 != Primitive::kPrimNot;
Fred Shih37f05ef2014-07-16 18:38:08 -07005045 if (type1 != type2) {
5046 if (is_primitive1 && is_primitive2) {
5047 // Larger primitive types go first.
5048 return Primitive::ComponentSize(type1) > Primitive::ComponentSize(type2);
5049 } else {
5050 // Reference always goes first.
5051 return !is_primitive1;
5052 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08005053 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005054 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005055 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005056 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005057 }
5058};
5059
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005060bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005061 size_t* class_size) {
5062 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005063 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005064 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005065
Brian Carlstromea46f952013-07-30 01:26:50 -07005066 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005067 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005068
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005069 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005070 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005071 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005072 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
5073 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
5074 // Static fields come after the embedded tables.
5075 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
Fred Shih37f05ef2014-07-16 18:38:08 -07005076 0, 0, 0, 0, 0);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005077 }
5078 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005079 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005080 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005081 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005082 CHECK(super_class->IsResolved())
5083 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005084 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005085 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005086 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005087
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005088 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005089
Brian Carlstromdbc05252011-09-09 01:59:59 -07005090 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005091 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005092 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005093 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005094 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005095 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005096 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005097 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005098 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005099 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005100 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5101 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005102
Fred Shih381e4ca2014-08-25 17:24:27 -07005103 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005104 size_t current_field = 0;
5105 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005106 FieldGaps gaps;
5107
Brian Carlstromdbc05252011-09-09 01:59:59 -07005108 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005109 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005110 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005111 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005112 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005113 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005114 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005115 if (UNLIKELY(!IsAligned<4>(field_offset.Uint32Value()))) {
5116 MemberOffset old_offset = field_offset;
5117 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5118 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5119 }
5120 DCHECK(IsAligned<4>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005121 grouped_and_sorted_fields.pop_front();
5122 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005123 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005124 field->SetOffset(field_offset);
5125 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005126 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005127 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5128 // otherwise we could end up with suboptimal gap fills.
5129 ShuffleForward<8>(num_fields, &current_field, &field_offset,
5130 fields, &grouped_and_sorted_fields, &gaps);
5131 ShuffleForward<4>(num_fields, &current_field, &field_offset,
5132 fields, &grouped_and_sorted_fields, &gaps);
5133 ShuffleForward<2>(num_fields, &current_field, &field_offset,
5134 fields, &grouped_and_sorted_fields, &gaps);
5135 ShuffleForward<1>(num_fields, &current_field, &field_offset,
5136 fields, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005137 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5138 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005139 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005140
Elliott Hughesadb460d2011-10-05 17:02:34 -07005141 // 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 -07005142 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005143 // We know there are no non-reference fields in the Reference classes, and we know
5144 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005145 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005146 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005147 --num_reference_fields;
5148 }
5149
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005150 if (kIsDebugBuild) {
5151 // Make sure that all reference fields appear before
5152 // non-reference fields, and all double-wide fields are aligned.
5153 bool seen_non_ref = false;
5154 for (size_t i = 0; i < num_fields; i++) {
5155 mirror::ArtField* field = fields->Get(i);
5156 if (false) { // enable to debug field layout
5157 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005158 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005159 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07005160 << " offset="
5161 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005162 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005163 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005164 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005165 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005166 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005167 is_primitive = true; // We lied above, so we have to expect a lie here.
5168 }
5169 if (is_primitive) {
5170 if (!seen_non_ref) {
5171 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07005172 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005173 }
5174 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07005175 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005176 }
5177 }
5178 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005179 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005180 }
5181 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005182
5183 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005184 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005185 if (is_static) {
5186 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005187 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005188 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005189 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005190 if (!klass->IsVariableSize()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005191 std::string temp;
5192 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005193 size_t previous_size = klass->GetObjectSize();
5194 if (previous_size != 0) {
5195 // Make sure that we didn't originally have an incorrect size.
Ian Rogers1ff3c982014-08-12 02:30:58 -07005196 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005197 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005198 klass->SetObjectSize(size);
5199 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005200 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005201 return true;
5202}
5203
5204// Set the bitmap of reference offsets, refOffsets, from the ifields
5205// list.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005206void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005207 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005208 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005209 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005210 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005211 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005212 // Compute reference offsets unless our superclass overflowed.
5213 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5214 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
5215 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
5216 // All of the fields that contain object references are guaranteed
5217 // to be at the beginning of the fields list.
5218 for (size_t i = 0; i < num_reference_fields; ++i) {
5219 // Note that byte_offset is the offset from the beginning of
5220 // object, not the offset into instance data
5221 mirror::ArtField* field = fields->Get(i);
5222 MemberOffset byte_offset = field->GetOffsetDuringLinking();
5223 uint32_t displaced_bitmap_position =
5224 (byte_offset.Uint32Value() - mirror::kObjectHeaderSize) /
5225 sizeof(mirror::HeapReference<mirror::Object>);
5226 if (displaced_bitmap_position >= 32) {
5227 // Can't encode offset so fall back on slow-path.
5228 reference_offsets = mirror::Class::kClassWalkSuper;
5229 break;
5230 } else {
5231 reference_offsets |= (1 << displaced_bitmap_position);
5232 }
5233 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005234 }
5235 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005236 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005237}
5238
Mathieu Chartier590fee92013-09-13 13:46:47 -07005239mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005240 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005241 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005242 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005243 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005244 return resolved;
5245 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005246 uint32_t utf16_length;
5247 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005248 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005249 dex_cache->SetResolvedString(string_idx, string);
5250 return string;
5251}
5252
Mathieu Chartier590fee92013-09-13 13:46:47 -07005253mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005254 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005255 StackHandleScope<2> hs(Thread::Current());
5256 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5257 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005258 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5259}
5260
5261mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005262 Handle<mirror::DexCache> dex_cache,
5263 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005264 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005265 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005266 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005267 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005268 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005269 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005270 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005271 // TODO: we used to throw here if resolved's class loader was not the
5272 // boot class loader. This was to permit different classes with the
5273 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005274 dex_cache->SetResolvedType(type_idx, resolved);
5275 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005276 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005277 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005278 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005279 StackHandleScope<1> hs(self);
5280 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005281 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005282 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005283 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005284 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005285 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005286 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005287 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005288 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005289 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005290 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005291 return resolved;
5292}
5293
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005294mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005295 Handle<mirror::DexCache> dex_cache,
5296 Handle<mirror::ClassLoader> class_loader,
5297 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005298 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005299 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005300 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005301 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005302 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005303 return resolved;
5304 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005305 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005306 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005307 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005308 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005309 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005310 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005311 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005312 // Scan using method_idx, this saves string compares but will only hit for matching dex
5313 // caches/files.
5314 switch (type) {
5315 case kDirect: // Fall-through.
5316 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005317 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005318 break;
5319 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005320 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005321 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005322 break;
5323 case kSuper: // Fall-through.
5324 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005325 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005326 break;
5327 default:
5328 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005329 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005330 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005331 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005332 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005333 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005334 switch (type) {
5335 case kDirect: // Fall-through.
5336 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005337 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005338 break;
5339 case kInterface:
5340 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005341 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005342 break;
5343 case kSuper: // Fall-through.
5344 case kVirtual:
5345 resolved = klass->FindVirtualMethod(name, signature);
5346 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005347 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005348 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005349 // If we found a method, check for incompatible class changes.
5350 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005351 // Be a good citizen and update the dex cache to speed subsequent calls.
5352 dex_cache->SetResolvedMethod(method_idx, resolved);
5353 return resolved;
5354 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005355 // If we had a method, it's an incompatible-class-change error.
5356 if (resolved != nullptr) {
5357 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5358 } else {
5359 // We failed to find the method which means either an access error, an incompatible class
5360 // change, or no such method. First try to find the method among direct and virtual methods.
5361 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5362 const Signature signature = dex_file.GetMethodSignature(method_id);
5363 switch (type) {
5364 case kDirect:
5365 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005366 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005367 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5368 // have had a resolved method before, which triggers the "true" branch above.
5369 break;
5370 case kInterface:
5371 case kVirtual:
5372 case kSuper:
5373 resolved = klass->FindDirectMethod(name, signature);
5374 break;
5375 }
5376
5377 // If we found something, check that it can be accessed by the referrer.
5378 if (resolved != nullptr && referrer.Get() != nullptr) {
5379 mirror::Class* methods_class = resolved->GetDeclaringClass();
5380 mirror::Class* referring_class = referrer->GetDeclaringClass();
5381 if (!referring_class->CanAccess(methods_class)) {
5382 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5383 resolved, type);
5384 return nullptr;
5385 } else if (!referring_class->CanAccessMember(methods_class,
5386 resolved->GetAccessFlags())) {
5387 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5388 return nullptr;
5389 }
5390 }
5391
5392 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5393 // methods and throw if we find the method there. If we find nothing, throw a
5394 // NoSuchMethodError.
5395 switch (type) {
5396 case kDirect:
5397 case kStatic:
5398 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005399 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005400 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005401 resolved = klass->FindInterfaceMethod(name, signature);
5402 if (resolved != nullptr) {
5403 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5404 } else {
5405 ThrowNoSuchMethodError(type, klass, name, signature);
5406 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005407 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005408 break;
5409 case kInterface:
5410 if (resolved != nullptr) {
5411 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005412 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005413 resolved = klass->FindVirtualMethod(name, signature);
5414 if (resolved != nullptr) {
5415 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5416 } else {
5417 ThrowNoSuchMethodError(type, klass, name, signature);
5418 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005419 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005420 break;
5421 case kSuper:
Andreas Gampedf733752014-08-25 20:55:01 -07005422 if (resolved != nullptr) {
5423 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5424 } else {
5425 ThrowNoSuchMethodError(type, klass, name, signature);
5426 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005427 break;
5428 case kVirtual:
5429 if (resolved != nullptr) {
5430 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5431 } else {
5432 resolved = klass->FindInterfaceMethod(name, signature);
5433 if (resolved != nullptr) {
5434 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5435 } else {
5436 ThrowNoSuchMethodError(type, klass, name, signature);
5437 }
5438 }
5439 break;
5440 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005441 }
5442 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005443 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005444 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005445}
5446
Mathieu Chartier590fee92013-09-13 13:46:47 -07005447mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005448 Handle<mirror::DexCache> dex_cache,
5449 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005450 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005451 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005452 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005453 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005454 return resolved;
5455 }
5456 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005457 Thread* const self = Thread::Current();
5458 StackHandleScope<1> hs(self);
5459 Handle<mirror::Class> klass(
5460 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005461 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005462 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005463 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005464 }
5465
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005466 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005467 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005468 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005469 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005470 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005471
Andreas Gampe58a5af82014-07-31 16:23:49 -07005472 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005473 const char* name = dex_file.GetFieldName(field_id);
5474 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5475 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005476 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005477 } else {
5478 resolved = klass->FindInstanceField(name, type);
5479 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005480 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005481 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005482 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005483 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005484 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005485 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005486 return resolved;
5487}
5488
Brian Carlstromea46f952013-07-30 01:26:50 -07005489mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005490 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005491 Handle<mirror::DexCache> dex_cache,
5492 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005493 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005494 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005495 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005496 return resolved;
5497 }
5498 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005499 Thread* self = Thread::Current();
5500 StackHandleScope<1> hs(self);
5501 Handle<mirror::Class> klass(
5502 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005503 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005504 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005505 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005506 }
5507
Ian Rogersdfb325e2013-10-30 01:00:44 -07005508 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5509 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005510 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005511 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005512 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005513 dex_cache->SetResolvedField(field_idx, resolved);
5514 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005515 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005516 }
5517 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005518}
5519
Brian Carlstromea46f952013-07-30 01:26:50 -07005520const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005521 uint32_t* length) {
5522 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5523 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005524 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005525 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005526 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005527}
5528
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005529void ClassLinker::DumpAllClasses(int flags) {
5530 if (dex_cache_image_class_lookup_required_) {
5531 MoveImageClassesToClassTable();
5532 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005533 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5534 // 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 -08005535 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005536 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005537 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005538 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5539 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005540 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005541 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005542 }
5543
5544 for (size_t i = 0; i < all_classes.size(); ++i) {
5545 all_classes[i]->DumpClass(std::cerr, flags);
5546 }
5547}
5548
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005549void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005550 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005551 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005552 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005553 MoveImageClassesToClassTable();
5554 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005555 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005556 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005557}
5558
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005559size_t ClassLinker::NumLoadedClasses() {
5560 if (dex_cache_image_class_lookup_required_) {
5561 MoveImageClassesToClassTable();
5562 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005563 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005564 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005565}
5566
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005567pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005568 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005569}
5570
5571pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005572 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005573}
5574
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005575void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005576 DCHECK(!init_done_);
5577
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005578 DCHECK(klass != nullptr);
5579 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005580
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005581 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005582 DCHECK(class_roots != nullptr);
5583 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005584 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005585}
5586
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005587} // namespace art