blob: fb90b911bd87a681797d32c6747519d3e936371f [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070020#include <iostream>
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070022#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070024#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070025#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070026
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080028#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010029#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080030#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080031#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000033#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080034#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070035#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070036#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070037#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
40#include "gc/heap.h"
41#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070042#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070043#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070044#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070045#include "leb128.h"
Ian Rogers1ff3c982014-08-12 02:30:58 -070046#include "method_helper-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080047#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070048#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070049#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070050#include "mirror/art_field-inl.h"
51#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/class.h"
53#include "mirror/class-inl.h"
54#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070055#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/object-inl.h"
58#include "mirror/object_array-inl.h"
59#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070060#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070062#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080063#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070064#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070065#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070066#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070067#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070068#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070069#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070070#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080071#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070072#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070073
74namespace art {
75
Ian Rogers00f7d0e2012-07-19 15:28:27 -070076static void ThrowNoClassDefFoundError(const char* fmt, ...)
77 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070078 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070079static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070080 va_list args;
81 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080082 Thread* self = Thread::Current();
83 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
84 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080085 va_end(args);
86}
87
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080088static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070090 // The class failed to initialize on a previous attempt, so we want to throw
91 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
92 // failed in verification, in which case v2 5.4.1 says we need to re-throw
93 // the previous error.
Ian Rogers7b078e82014-09-10 14:44:24 -070094 Runtime* runtime = Runtime::Current();
95 bool is_compiler = runtime->IsCompiler();
96 if (!is_compiler) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070097 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
98 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070099
Elliott Hughes5c599942012-06-13 16:45:05 -0700100 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800101 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700102 if (is_compiler) {
103 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
104 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
105 self->SetException(ThrowLocation(), pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700106 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700107 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
108 if (c->GetVerifyErrorClass() != NULL) {
109 // TODO: change the verifier to store an _instance_, with a useful detail message?
110 std::string temp;
111 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
112 PrettyDescriptor(c).c_str());
113 } else {
114 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
115 PrettyDescriptor(c).c_str());
116 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700117 }
118}
119
Brian Carlstromb23eab12014-10-08 17:55:21 -0700120static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
121 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
122 if (VLOG_IS_ON(class_linker)) {
123 std::string temp;
124 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
125 << klass->GetLocation() << "\n" << Thread::Current()->GetException(nullptr)->Dump();
126 }
127}
128
129static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
130 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700131 Thread* self = Thread::Current();
132 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700133
134 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700135 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700136
137 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700138 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
139 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700140
Elliott Hughesa4f94742012-05-29 16:28:38 -0700141 // We only wrap non-Error exceptions; an Error can just be used as-is.
142 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800143 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700144 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
145 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700146 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700147 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700148}
149
Fred Shih381e4ca2014-08-25 17:24:27 -0700150// Gap between two fields in object layout.
151struct FieldGap {
152 uint32_t start_offset; // The offset from the start of the object.
153 uint32_t size; // The gap size of 1, 2, or 4 bytes.
154};
155struct FieldGapsComparator {
156 explicit FieldGapsComparator() {
157 }
158 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
159 NO_THREAD_SAFETY_ANALYSIS {
160 // Sort by gap size, largest first.
161 return lhs.size > rhs.size;
162 }
163};
164typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
165
166// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800167static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700168 DCHECK(gaps != nullptr);
169
170 uint32_t current_offset = gap_start;
171 while (current_offset != gap_end) {
172 size_t remaining = gap_end - current_offset;
173 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
174 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
175 current_offset += sizeof(uint32_t);
176 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
177 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
178 current_offset += sizeof(uint16_t);
179 } else {
180 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
181 current_offset += sizeof(uint8_t);
182 }
183 DCHECK_LE(current_offset, gap_end) << "Overran gap";
184 }
185}
186// Shuffle fields forward, making use of gaps whenever possible.
187template<int n>
188static void ShuffleForward(const size_t num_fields, size_t* current_field_idx,
189 MemberOffset* field_offset,
190 mirror::ObjectArray<mirror::ArtField>* fields,
191 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
192 FieldGaps* gaps)
193 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
194 DCHECK(current_field_idx != nullptr);
195 DCHECK(grouped_and_sorted_fields != nullptr);
196 DCHECK(fields != nullptr || (num_fields == 0 && grouped_and_sorted_fields->empty()));
197 DCHECK(gaps != nullptr);
198 DCHECK(field_offset != nullptr);
199
200 DCHECK(IsPowerOfTwo(n));
201 while (!grouped_and_sorted_fields->empty()) {
202 mirror::ArtField* field = grouped_and_sorted_fields->front();
203 Primitive::Type type = field->GetTypeAsPrimitiveType();
204 if (Primitive::ComponentSize(type) < n) {
205 break;
206 }
207 if (!IsAligned<n>(field_offset->Uint32Value())) {
208 MemberOffset old_offset = *field_offset;
209 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
210 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
211 }
212 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
213 grouped_and_sorted_fields->pop_front();
214 fields->Set<false>(*current_field_idx, field);
215 if (!gaps->empty() && gaps->top().size >= n) {
216 FieldGap gap = gaps->top();
217 gaps->pop();
218 DCHECK(IsAligned<n>(gap.start_offset));
219 field->SetOffset(MemberOffset(gap.start_offset));
220 if (gap.size > n) {
221 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
222 }
223 } else {
224 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
225 field->SetOffset(*field_offset);
226 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
227 }
228 ++(*current_field_idx);
229 }
230}
231
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800232ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700233 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700234 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700235 dex_cache_image_class_lookup_required_(false),
236 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800237 class_roots_(nullptr),
238 array_iftable_(nullptr),
239 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700240 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800241 log_new_dex_caches_roots_(false),
242 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700243 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800244 portable_resolution_trampoline_(nullptr),
245 quick_resolution_trampoline_(nullptr),
246 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800247 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100248 quick_generic_jni_trampoline_(nullptr),
249 quick_to_interpreter_bridge_trampoline_(nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -0800250 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700251}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700252
Alex Light64ad14d2014-08-19 14:23:13 -0700253void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800254 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700255 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700256
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700257 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700258
Elliott Hughes30646832011-10-13 16:59:46 -0700259 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700260 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700261 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700262 // 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 -0800263 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700264 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
265 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700266 heap->AllocNonMovableObject<true>(self, nullptr,
267 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700268 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700269 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700270 mirror::Class::SetClassClass(java_lang_Class.Get());
271 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700272 if (kUseBakerOrBrooksReadBarrier) {
273 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800274 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700275 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700276 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800277 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800278 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700279
Elliott Hughes418d20f2011-09-22 14:00:39 -0700280 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700281 Handle<mirror::Class> class_array_class(hs.NewHandle(
282 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700283 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700284
Ian Rogers23435d02012-09-24 11:23:12 -0700285 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700286 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
287 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700288 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700289 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700290 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700291 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700292
Ian Rogers23435d02012-09-24 11:23:12 -0700293 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700294 Handle<mirror::Class> object_array_class(hs.NewHandle(
295 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700296 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700297
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700298 // Setup the char (primitive) class to be used for char[].
299 Handle<mirror::Class> char_class(hs.NewHandle(
300 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700301 // The primitive char class won't be initialized by
302 // InitializePrimitiveClass until line 459, but strings (and
303 // internal char arrays) will be allocated before that and the
304 // component size, which is computed from the primitive type, needs
305 // to be set here.
306 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700307
Ian Rogers23435d02012-09-24 11:23:12 -0700308 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700309 Handle<mirror::Class> char_array_class(hs.NewHandle(
310 AllocClass(self, java_lang_Class.Get(),
311 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700312 char_array_class->SetComponentType(char_class.Get());
313 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700314
Ian Rogers23435d02012-09-24 11:23:12 -0700315 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700316 Handle<mirror::Class> java_lang_String(hs.NewHandle(
317 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700318 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700319 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700320 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400321
Fred Shih4ee7a662014-07-11 09:59:27 -0700322 // Setup Reference.
323 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
324 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
325 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
326 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
327 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
328
Ian Rogers23435d02012-09-24 11:23:12 -0700329 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700330 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
331 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
332 kClassRootsMax));
333 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700334 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
335 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
336 SetClassRoot(kClassArrayClass, class_array_class.Get());
337 SetClassRoot(kObjectArrayClass, object_array_class.Get());
338 SetClassRoot(kCharArrayClass, char_array_class.Get());
339 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700340 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700341
342 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700343 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
344 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
345 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
346 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
347 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
348 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
349 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
350 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351
Ian Rogers23435d02012-09-24 11:23:12 -0700352 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700353 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354
Ian Rogers23435d02012-09-24 11:23:12 -0700355 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700356 Handle<mirror::Class> int_array_class(hs.NewHandle(
357 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700359 mirror::IntArray::SetArrayClass(int_array_class.Get());
360 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700361
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700362 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700363
Ian Rogers52813c92012-10-11 11:50:38 -0700364 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700365 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
366 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700367 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700368 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700369 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700370
Brian Carlstromf3632832014-05-20 15:36:53 -0700371 // Constructor, Field, Method, and AbstractMethod are necessary so
372 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700373 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
374 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700375 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700376 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700377 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700378 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700379 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700380
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700381 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
382 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700383 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700384 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700385 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700386 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700387
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700388 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700389
390 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700391 Handle<mirror::Class> object_array_string(hs.NewHandle(
392 AllocClass(self, java_lang_Class.Get(),
393 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700394 object_array_string->SetComponentType(java_lang_String.Get());
395 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700396
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700397 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
398 AllocClass(self, java_lang_Class.Get(),
399 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700400 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
401 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700402
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700403 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
404 AllocClass(self, java_lang_Class.Get(),
405 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700406 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
407 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700408
Ian Rogers23435d02012-09-24 11:23:12 -0700409 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
410 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
411 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700412 CHECK_NE(0U, boot_class_path.size());
413 for (size_t i = 0; i != boot_class_path.size(); ++i) {
414 const DexFile* dex_file = boot_class_path[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700415 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700416 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700417 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700418
419 // now we can use FindSystemClass
420
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700421 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700422 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
423 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700424
Jeff Hao88474b42013-10-23 16:24:40 -0700425 // Create runtime resolution and imt conflict methods. Also setup the default imt.
426 Runtime* runtime = Runtime::Current();
427 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
428 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700429 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700430 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
431
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700432 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
433 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700434 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700435 if (!runtime->IsCompiler()) {
436 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700437 quick_resolution_trampoline_ = GetQuickResolutionStub();
438 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
439 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700440 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700441
Mathieu Chartier66f19252012-09-18 08:57:04 -0700442 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700443 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800444 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700445 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700446 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700447 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800448 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700449 std::ostringstream os1, os2;
450 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
451 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
452 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
453 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700454 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800455 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700456 CHECK_EQ(java_lang_String.Get(), String_class);
457 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700458 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459
Ian Rogers23435d02012-09-24 11:23:12 -0700460 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800461 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800462 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700463
Ian Rogers98379392014-02-24 16:53:16 -0800464 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800465 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700466
Ian Rogers98379392014-02-24 16:53:16 -0800467 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700468 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700469
Ian Rogers98379392014-02-24 16:53:16 -0800470 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800471 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700472
Ian Rogers98379392014-02-24 16:53:16 -0800473 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700474 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475
Ian Rogers98379392014-02-24 16:53:16 -0800476 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800477 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700478
Ian Rogers98379392014-02-24 16:53:16 -0800479 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800480 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700481
Ian Rogers98379392014-02-24 16:53:16 -0800482 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800483 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700484
Ian Rogers98379392014-02-24 16:53:16 -0800485 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700486 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700487
Ian Rogers98379392014-02-24 16:53:16 -0800488 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700489 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700490
Ian Rogers23435d02012-09-24 11:23:12 -0700491 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800492 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700493 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800494 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700495 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700496 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
497 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700498 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700499 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700500 array_iftable->SetInterface(0, java_lang_Cloneable);
501 array_iftable->SetInterface(1, java_io_Serializable);
502 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700503
Ian Rogers23435d02012-09-24 11:23:12 -0700504 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700505 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
506 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
507 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
508 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700509 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700510 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800511 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700512 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700513
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700514 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800515 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700516 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700517
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700518 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800519 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700520 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700521
Brian Carlstromf3632832014-05-20 15:36:53 -0700522 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700523 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700524 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700525
Brian Carlstromea46f952013-07-30 01:26:50 -0700526 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700527 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700528 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700529
Brian Carlstromea46f952013-07-30 01:26:50 -0700530 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700531 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700532 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700533
Ian Rogers23435d02012-09-24 11:23:12 -0700534 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700535
Ian Rogers23435d02012-09-24 11:23:12 -0700536 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800537 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700538 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
539
Brian Carlstrom1f870082011-08-23 16:02:11 -0700540 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700541 // finish initializing Reference class
542 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
543 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
544 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
545 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
546 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700547 mirror::Class* java_lang_ref_FinalizerReference =
548 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700549 java_lang_ref_FinalizerReference->SetAccessFlags(
550 java_lang_ref_FinalizerReference->GetAccessFlags() |
551 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700552 mirror::Class* java_lang_ref_PhantomReference =
553 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554 java_lang_ref_PhantomReference->SetAccessFlags(
555 java_lang_ref_PhantomReference->GetAccessFlags() |
556 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700557 mirror::Class* java_lang_ref_SoftReference =
558 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 java_lang_ref_SoftReference->SetAccessFlags(
560 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700561 mirror::Class* java_lang_ref_WeakReference =
562 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700563 java_lang_ref_WeakReference->SetAccessFlags(
564 java_lang_ref_WeakReference->GetAccessFlags() |
565 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700566
Ian Rogers23435d02012-09-24 11:23:12 -0700567 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800568 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700569 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700570 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
571
jeffhao8cd6dda2012-02-22 10:15:34 -0800572 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700573 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800574 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800575 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700576 SetClassRoot(kJavaLangClassNotFoundException,
577 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800578 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700579 SetClassRoot(kJavaLangStackTraceElementArrayClass,
580 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800581 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700582
Ian Rogers98379392014-02-24 16:53:16 -0800583 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700584
Brian Carlstroma004aa92012-02-08 18:05:09 -0800585 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700586}
587
Ian Rogers98379392014-02-24 16:53:16 -0800588void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800589 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700590
591 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700592 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700593 // as the types of the field can't be resolved prior to the runtime being
594 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800595 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700596 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800597 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800598
Brian Carlstromea46f952013-07-30 01:26:50 -0700599 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700600 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
601 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700602
Brian Carlstromea46f952013-07-30 01:26:50 -0700603 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700604 CHECK_STREQ(queue->GetName(), "queue");
605 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700606
Brian Carlstromea46f952013-07-30 01:26:50 -0700607 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700608 CHECK_STREQ(queueNext->GetName(), "queueNext");
609 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700610
Brian Carlstromea46f952013-07-30 01:26:50 -0700611 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700612 CHECK_STREQ(referent->GetName(), "referent");
613 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700614
Brian Carlstromea46f952013-07-30 01:26:50 -0700615 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700616 CHECK_STREQ(zombie->GetName(), "zombie");
617 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700618
Brian Carlstroma663ea52011-08-19 23:33:41 -0700619 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700620 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700621 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800622 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700623 CHECK(klass != nullptr);
624 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700625 // note SetClassRoot does additional validation.
626 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700627 }
628
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700629 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700630
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700631 // disable the slow paths in FindClass and CreatePrimitiveClass now
632 // that Object, Class, and Object[] are setup
633 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700634
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800635 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700636}
637
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700638void ClassLinker::RunRootClinits() {
639 Thread* self = Thread::Current();
640 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800641 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700642 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700643 StackHandleScope<1> hs(self);
644 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700645 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700646 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700647 }
648 }
649}
650
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700651bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800652 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000653 const char* oat_cache_filename,
654 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700655 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700656 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800657
Ian Rogers1d54e732013-05-02 21:10:01 -0700658 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800659 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700660 if (heap->GetImageSpace() == nullptr) {
661 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
662 // out of space anyway it might not matter.
663 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
664 "without an image.", dex_filename);
665 return false;
666 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700667 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800668
Brian Carlstrom6449c622014-02-10 23:48:36 -0800669 std::string dex_file_option("--dex-file=");
670 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800671
Brian Carlstrom6449c622014-02-10 23:48:36 -0800672 std::string oat_fd_option("--oat-fd=");
673 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800674
Brian Carlstrom6449c622014-02-10 23:48:36 -0800675 std::string oat_location_option("--oat-location=");
676 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800677
Brian Carlstrom6449c622014-02-10 23:48:36 -0800678 std::vector<std::string> argv;
679 argv.push_back(dex2oat);
680 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800681 argv.push_back("-classpath");
682 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800683 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800684
Ian Rogers8afeb852014-04-02 14:55:49 -0700685 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800686
Jeff Hao4a200f52014-04-01 14:58:49 -0700687 if (!Runtime::Current()->IsVerificationEnabled()) {
688 argv.push_back("--compiler-filter=verify-none");
689 }
690
Alex Light6e183f22014-07-18 14:57:04 -0700691 if (Runtime::Current()->MustRelocateIfPossible()) {
692 argv.push_back("--runtime-arg");
693 argv.push_back("-Xrelocate");
694 } else {
695 argv.push_back("--runtime-arg");
696 argv.push_back("-Xnorelocate");
697 }
698
Brian Carlstrom6449c622014-02-10 23:48:36 -0800699 if (!kIsTargetBuild) {
700 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700701 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700702
Brian Carlstrom6449c622014-02-10 23:48:36 -0800703 argv.push_back(boot_image_option);
704 argv.push_back(dex_file_option);
705 argv.push_back(oat_fd_option);
706 argv.push_back(oat_location_option);
707 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800708 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800709 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700710 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800711
712 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700713}
714
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700715const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700716 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800717 if (kIsDebugBuild) {
718 for (size_t i = 0; i < oat_files_.size(); ++i) {
719 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700720 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800721 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700722 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
723 oat_files_.push_back(oat_file);
724 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800725}
726
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700727OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
728 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700729 OatFile* oat_file = space->ReleaseOatFile();
730 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700731 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700732 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700733}
734
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100735const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800736 const char* dex_location = dex_file.GetLocation().c_str();
737 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100738 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800739}
740
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100741const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
742 const char* dex_location,
743 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700744 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100745 for (const OatFile* oat_file : oat_files_) {
746 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700747
748 if (oat_location != nullptr) {
749 if (oat_file->GetLocation() != oat_location) {
750 continue;
751 }
752 }
753
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700754 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800755 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700756 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100757 if (oat_dex_file != nullptr) {
758 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800759 }
760 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100761 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800762}
763
Calin Juravle621962a2014-09-02 15:53:55 +0100764
765// Loads all multi dex files from the given oat file returning true on success.
766//
767// Parameters:
768// oat_file - the oat file to load from
769// dex_location - the dex location used to generate the oat file
770// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
771// generated - whether or not the oat_file existed before or was just (re)generated
772// error_msgs - any error messages will be appended here
773// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
774static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
775 const char* dex_location,
776 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700777 bool generated,
778 std::vector<std::string>* error_msgs,
779 std::vector<const DexFile*>* dex_files) {
780 if (oat_file == nullptr) {
781 return false;
782 }
783
784 size_t old_size = dex_files->size(); // To rollback on error.
785
786 bool success = true;
787 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100788 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700789 const char* next_name = next_name_str.c_str();
790
Calin Juravle621962a2014-09-02 15:53:55 +0100791 uint32_t next_location_checksum;
792 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700793 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100794 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
795 // When i=0 the multidex name should be the same as the location name. We already have the
796 // checksum it so we don't need to recompute it.
797 if (dex_location_checksum == nullptr) {
798 next_location_checksum_pointer = nullptr;
799 } else {
800 next_location_checksum = *dex_location_checksum;
801 }
802 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700803 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100804 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700805 }
806
807 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
808
809 if (oat_dex_file == nullptr) {
810 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700811 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100812 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700813 oat_file->GetLocation().c_str());
814 error_msgs->push_back(error_msg);
815 }
816 break; // Not found, done.
817 }
818
819 // Checksum test. Test must succeed when generated.
820 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100821 if (next_location_checksum_pointer != nullptr) {
822 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700823 }
824
825 if (success) {
826 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
827 if (dex_file == nullptr) {
828 success = false;
829 error_msgs->push_back(error_msg);
830 } else {
831 dex_files->push_back(dex_file);
832 }
833 }
834
835 // When we generated the file, we expect success, or something is terribly wrong.
836 CHECK_EQ(false, generated && !success)
837 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100838 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700839 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
840 }
841
842 if (dex_files->size() == old_size) {
843 success = false; // We did not even find classes.dex
844 }
845
846 if (success) {
847 return true;
848 } else {
849 // Free all the dex files we have loaded.
850 auto it = dex_files->begin() + old_size;
851 auto it_end = dex_files->end();
852 for (; it != it_end; it++) {
853 delete *it;
854 }
855 dex_files->erase(dex_files->begin() + old_size, it_end);
856
857 return false;
858 }
859}
860
861// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
862// complicates the loading process, as we should not use an iterative loading process, because that
863// would register the oat file and dex files that come before the broken one. Instead, check all
864// multidex ahead of time.
865bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
866 std::vector<std::string>* error_msgs,
867 std::vector<const DexFile*>* dex_files) {
868 // 1) Check whether we have an open oat file.
869 // This requires a dex checksum, use the "primary" one.
870 uint32_t dex_location_checksum;
871 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
872 bool have_checksum = true;
873 std::string checksum_error_msg;
874 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100875 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700876 dex_location_checksum_pointer = nullptr;
877 have_checksum = false;
878 }
879
880 bool needs_registering = false;
881
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100882 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
883 dex_location_checksum_pointer);
884 std::unique_ptr<const OatFile> open_oat_file(
885 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700886
887 // 2) If we do not have an open one, maybe there's one on disk already.
888
889 // In case the oat file is not open, we play a locking game here so
890 // that if two different processes race to load and register or generate
891 // (or worse, one tries to open a partial generated file) we will be okay.
892 // This is actually common with apps that use DexClassLoader to work
893 // around the dex method reference limit and that have a background
894 // service running in a separate process.
895 ScopedFlock scoped_flock;
896
897 if (open_oat_file.get() == nullptr) {
898 if (oat_location != nullptr) {
899 // Can only do this if we have a checksum, else error.
900 if (!have_checksum) {
901 error_msgs->push_back(checksum_error_msg);
902 return false;
903 }
904
905 std::string error_msg;
906
907 // We are loading or creating one in the future. Time to set up the file lock.
908 if (!scoped_flock.Init(oat_location, &error_msg)) {
909 error_msgs->push_back(error_msg);
910 return false;
911 }
912
Alex Lighta59dd802014-07-02 16:28:08 -0700913 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700914 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
915 oat_location, &error_msg));
916
917 if (open_oat_file.get() == nullptr) {
918 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
919 dex_location, oat_location, error_msg.c_str());
920 VLOG(class_linker) << compound_msg;
921 error_msgs->push_back(compound_msg);
922 }
923 } else {
924 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100925 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700926 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
927 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100928 kRuntimeISA, error_msgs,
929 &obsolete_file_cleanup_failed));
930 // There's no point in going forward and eventually try to regenerate the
931 // file if we couldn't remove the obsolete one. Mostly likely we will fail
932 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100933 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
934 if (obsolete_file_cleanup_failed) {
935 return false;
936 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700937 }
938 needs_registering = true;
939 }
940
941 // 3) If we have an oat file, check all contained multidex files for our dex_location.
942 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100943 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
944 dex_location_checksum_pointer,
945 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700946 if (success) {
947 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
948 if (needs_registering) {
949 // We opened the oat file, so we must register it.
950 RegisterOatFile(oat_file);
951 }
Alex Light9dcc4572014-08-14 14:16:26 -0700952 // If the file isn't executable we failed patchoat but did manage to get the dex files.
953 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700954 } else {
955 if (needs_registering) {
956 // We opened it, delete it.
957 open_oat_file.reset();
958 } else {
959 open_oat_file.release(); // Do not delete open oat files.
960 }
961 }
962
963 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
964
965 // Need a checksum, fail else.
966 if (!have_checksum) {
967 error_msgs->push_back(checksum_error_msg);
968 return false;
969 }
970
971 // Look in cache location if no oat_location is given.
972 std::string cache_location;
973 if (oat_location == nullptr) {
974 // Use the dalvik cache.
975 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
976 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
977 oat_location = cache_location.c_str();
978 }
979
Alex Light64ad14d2014-08-19 14:23:13 -0700980 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700981 // Definitely need to lock now.
982 if (!scoped_flock.HasFile()) {
983 std::string error_msg;
984 if (!scoped_flock.Init(oat_location, &error_msg)) {
985 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700986 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700987 }
988 }
989
Alex Light64ad14d2014-08-19 14:23:13 -0700990 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +0100991 // Create the oat file.
992 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
993 oat_location, error_msgs));
994 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700995
996 // Failed, bail.
997 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +0100998 std::string error_msg;
999 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1000 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1001 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001002 return false;
1003 }
1004
1005 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001006 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1007 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001008 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001009 if (success) {
1010 RegisterOatFile(open_oat_file.release());
1011 return true;
1012 } else {
1013 return false;
1014 }
1015}
1016
1017const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1018 uint32_t dex_location_checksum,
1019 const char* oat_location,
1020 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001021 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001022 !Runtime::Current()->IsCompiler(),
1023 error_msg));
1024 if (oat_file.get() == nullptr) {
1025 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1026 error_msg->c_str());
1027 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001028 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001029 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001030 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1031 if (image_space != nullptr) {
1032 const ImageHeader& image_header = image_space->GetImageHeader();
1033 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1034 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1035 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1036 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1037 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1038 actual_image_oat_checksum);
1039 return nullptr;
1040 }
1041
1042 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1043 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1044 if (expected_image_oat_offset != actual_image_oat_offset) {
1045 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1046 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1047 actual_image_oat_offset);
1048 return nullptr;
1049 }
1050 int32_t expected_patch_delta = image_header.GetPatchDelta();
1051 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1052 if (expected_patch_delta != actual_patch_delta) {
1053 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1054 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1055 return nullptr;
1056 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001057 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001058
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001059 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1060 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001061 if (oat_dex_file == nullptr) {
1062 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1063 dex_location);
1064 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001065 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001066 uint32_t expected_dex_checksum = dex_location_checksum;
1067 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1068 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001069 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1070 "found 0x%x", oat_location, expected_dex_checksum,
1071 actual_dex_checksum);
1072 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001073 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001074 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1075 if (dex_file.get() != nullptr) {
1076 return oat_file.release();
1077 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001078 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001079 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001080}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001081
Andreas Gampe833a4852014-05-21 18:46:59 -07001082const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1083 int fd, const char* oat_location,
1084 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001085 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001086 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001087 std::string error_msg;
1088 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001089 CHECK(!error_msg.empty());
1090 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001091 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001092 }
Igor Murashkin46774762014-10-22 11:37:02 -07001093 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001094 !Runtime::Current()->IsCompiler(),
1095 &error_msg));
1096 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001097 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1098 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001099 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001100 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001101 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001102
1103 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001104}
1105
Alex Light6e183f22014-07-18 14:57:04 -07001106bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1107 const InstructionSet instruction_set) {
1108 Runtime* runtime = Runtime::Current();
1109 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001110 if (image_space == nullptr) {
1111 return false;
1112 }
Alex Light6e183f22014-07-18 14:57:04 -07001113 uint32_t image_oat_checksum = 0;
1114 if (instruction_set == kRuntimeISA) {
1115 const ImageHeader& image_header = image_space->GetImageHeader();
1116 image_oat_checksum = image_header.GetOatChecksum();
1117 } else {
1118 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1119 image_space->GetImageLocation().c_str(), instruction_set));
1120 image_oat_checksum = image_header->GetOatChecksum();
1121 }
1122 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1123}
1124
1125bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1126 const InstructionSet instruction_set,
1127 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001128 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001129 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001130 if (image_space == nullptr) {
1131 *error_msg = "No image space for verification against";
1132 return false;
1133 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001134
1135 // If the requested instruction set is the same as the current runtime,
1136 // we can use the checksums directly. If it isn't, we'll have to read the
1137 // image header from the image for the right instruction set.
1138 uint32_t image_oat_checksum = 0;
1139 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001140 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001141 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001142 const ImageHeader& image_header = image_space->GetImageHeader();
1143 image_oat_checksum = image_header.GetOatChecksum();
1144 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001145 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001146 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001147 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001148 image_space->GetImageLocation().c_str(), instruction_set));
1149 image_oat_checksum = image_header->GetOatChecksum();
1150 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001151 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001152 }
1153 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001154 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1155
1156 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1157 if (!oat_file->IsPic()) {
1158 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1159 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1160 }
Alex Light6e183f22014-07-18 14:57:04 -07001161 if (!ret) {
1162 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1163 oat_file->GetLocation().c_str(),
1164 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1165 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1166 oat_file->GetOatHeader().GetImagePatchDelta(),
1167 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1168 }
1169 return ret;
1170}
1171
1172bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1173 const char* dex_location,
1174 uint32_t dex_location_checksum,
1175 const InstructionSet instruction_set,
1176 std::string* error_msg) {
1177 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1178 return false;
1179 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001180
Brian Carlstromf3632832014-05-20 15:36:53 -07001181 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1182 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001183 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001184 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1185 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001186 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001187 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001188 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001189 oat_dex_file_in->GetDexFileLocation().c_str(),
1190 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001191 }
1192 return false;
1193 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001194
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001195 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001196 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001197}
1198
Alex Lighta59dd802014-07-02 16:28:08 -07001199bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1200 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001201 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001202 std::string* error_msg) {
1203 CHECK(oat_file != nullptr);
1204 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001205 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001206 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001207 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1208 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1209 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001210 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001211 if (oat_dex_file == nullptr) {
1212 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001213 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001214 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001215 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001216 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001217 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001218 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001219 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001220 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001221 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001222 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001223 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001224 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001225 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001226 }
Alex Lighta59dd802014-07-02 16:28:08 -07001227 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001228}
1229
Andreas Gampe833a4852014-05-21 18:46:59 -07001230const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001231 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001232 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001233 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001234 std::vector<std::string>* error_msgs,
1235 bool* obsolete_file_cleanup_failed) {
1236 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001237 bool already_opened = false;
1238 std::string dex_location_str(dex_location);
1239 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1240 &already_opened,
1241 obsolete_file_cleanup_failed,
1242 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001243 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001244 if (oat_file.get() == nullptr) {
1245 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1246 dex_location));
1247 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001248 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001249 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1250 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001251 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1252 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001253 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001254 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001255 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001256 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001257 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1258 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1259 "dex location '%s'. Image checksum incorrect.",
1260 oat_file->GetLocation().c_str(), dex_location));
1261 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001262 } else {
1263 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001264 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001265}
1266
Brian Carlstromae826982011-11-09 01:33:42 -08001267const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001268 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001269 for (size_t i = 0; i < oat_files_.size(); i++) {
1270 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001271 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001272 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001273 return oat_file;
1274 }
1275 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001276 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001277}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001278
Alex Lighta59dd802014-07-02 16:28:08 -07001279const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1280 InstructionSet isa,
1281 bool *already_opened,
1282 bool *obsolete_file_cleanup_failed,
1283 std::vector<std::string>* error_msgs) {
1284 // Find out if we've already opened the file
1285 const OatFile* ret = nullptr;
1286 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1287 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1288 if (ret != nullptr) {
1289 *already_opened = true;
1290 return ret;
1291 }
1292
1293 std::string dalvik_cache;
1294 bool have_android_data = false;
1295 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001296 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001297 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001298 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001299 std::string cache_filename;
1300 if (have_dalvik_cache) {
1301 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1302 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1303 if (ret != nullptr) {
1304 *already_opened = true;
1305 return ret;
1306 }
1307 } else {
1308 // If we need to relocate we should just place odex back where it started.
1309 cache_filename = odex_filename;
1310 }
1311
1312 ret = nullptr;
1313
1314 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1315 //
1316 // Now we do the following:
1317 // 1) Try and open the odex version
1318 // 2) If present, checksum-verified & relocated correctly return it
1319 // 3) Close the odex version to free up its address space.
1320 // 4) Try and open the cache version
1321 // 5) If present, checksum-verified & relocated correctly return it
1322 // 6) Close the cache version to free up its address space.
1323 // 7) If we should relocate:
1324 // a) If we have opened and checksum-verified the odex version relocate it to
1325 // 'cache_filename' and return it
1326 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1327 // it. This should not happen often (I think only the run-test's will hit this case).
1328 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1329 // this point.
1330 // 9) Return nullptr
1331
1332 *already_opened = false;
1333 const Runtime* runtime = Runtime::Current();
1334 CHECK(runtime != nullptr);
1335 bool executable = !runtime->IsCompiler();
1336
1337 std::string odex_error_msg;
1338 bool should_patch_system = false;
1339 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001340 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001341 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001342 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001343 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001344 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001345 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001346 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001347 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001348 &odex_checksum_verified,
1349 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001350 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001351 } else {
1352 if (odex_checksum_verified) {
1353 // We can just relocate
1354 should_patch_system = true;
1355 odex_error_msg = "Image Patches are incorrect";
1356 }
1357 if (odex_oat_file.get() != nullptr) {
1358 have_system_odex = true;
1359 }
Alex Lighta59dd802014-07-02 16:28:08 -07001360 }
1361 }
1362
Alex Lighta59dd802014-07-02 16:28:08 -07001363 std::string cache_error_msg;
1364 bool should_patch_cache = false;
1365 bool cache_checksum_verified = false;
1366 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001367 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001368 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001369 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001370 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001371 &cache_checksum_verified,
1372 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001373 return cache_oat_file.release();
1374 } else if (cache_checksum_verified) {
1375 // We can just relocate
1376 should_patch_cache = true;
1377 cache_error_msg = "Image Patches are incorrect";
1378 }
1379 } else if (have_android_data) {
1380 // dalvik_cache does not exist but android data does. This means we should be able to create
1381 // it, so we should try.
1382 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1383 }
1384
1385 ret = nullptr;
1386 std::string error_msg;
1387 if (runtime->CanRelocate()) {
1388 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001389 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1390 if (space != nullptr) {
1391 const std::string& image_location = space->GetImageLocation();
1392 if (odex_checksum_verified && should_patch_system) {
1393 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1394 } else if (cache_checksum_verified && should_patch_cache) {
1395 CHECK(have_dalvik_cache);
1396 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1397 }
Alex Light84d76052014-08-22 17:49:35 -07001398 } else if (have_system_odex) {
1399 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001400 }
1401 }
1402 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1403 // implicitly: were able to fine where the cached version is but we were unable to use it,
1404 // either as a destination for relocation or to open a file. We should delete it if it is
1405 // there.
1406 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1407 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1408 "searching for dex file %s: %s",
1409 cache_filename.c_str(), dex_location.c_str(),
1410 strerror(errno));
1411 error_msgs->push_back(rm_error_msg);
1412 VLOG(class_linker) << rm_error_msg;
1413 // Let the caller know that we couldn't remove the obsolete file.
1414 // This is a good indication that further writes may fail as well.
1415 *obsolete_file_cleanup_failed = true;
1416 }
1417 }
1418 if (ret == nullptr) {
1419 VLOG(class_linker) << error_msg;
1420 error_msgs->push_back(error_msg);
1421 std::string relocation_msg;
1422 if (runtime->CanRelocate()) {
1423 relocation_msg = StringPrintf(" and relocation failed");
1424 }
1425 if (have_dalvik_cache && cache_checksum_verified) {
1426 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1427 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1428 cache_filename.c_str(), cache_error_msg.c_str(),
1429 relocation_msg.c_str());
1430 } else {
1431 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1432 "dalvik_cache availible)%s.", odex_filename.c_str(),
1433 odex_error_msg.c_str(), relocation_msg.c_str());
1434 }
1435 VLOG(class_linker) << error_msg;
1436 error_msgs->push_back(error_msg);
1437 }
1438 return ret;
1439}
1440
Alex Light9dcc4572014-08-14 14:16:26 -07001441const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1442 InstructionSet isa,
1443 std::string* error_msg) {
1444 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001445 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001446 if (output.get() == nullptr) {
1447 return nullptr;
1448 }
Alex Light84d76052014-08-22 17:49:35 -07001449 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1450 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001451 return output.release();
1452 } else {
1453 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1454 oat_path.c_str());
1455 return nullptr;
1456 }
1457}
1458
Alex Lighta59dd802014-07-02 16:28:08 -07001459const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1460 const std::string& output_oat,
1461 const std::string& image_location,
1462 InstructionSet isa,
1463 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001464 Runtime* runtime = Runtime::Current();
1465 DCHECK(runtime != nullptr);
1466 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001467 // We don't have an image space so there is no point in trying to patchoat.
1468 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1469 << "running without an image. Attempting to use oat file for interpretation.";
1470 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1471 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001472 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001473 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1474 // input_oat but make sure we only do interpretation on it's dex files.
1475 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1476 << "disabled. Attempting to use oat file for interpretation";
1477 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1478 }
Alex Lighta59dd802014-07-02 16:28:08 -07001479 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001480 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001481
1482 std::string isa_arg("--instruction-set=");
1483 isa_arg += GetInstructionSetString(isa);
1484 std::string input_oat_filename_arg("--input-oat-file=");
1485 input_oat_filename_arg += input_oat;
1486 std::string output_oat_filename_arg("--output-oat-file=");
1487 output_oat_filename_arg += output_oat;
1488 std::string patched_image_arg("--patched-image-location=");
1489 patched_image_arg += image_location;
1490
1491 std::vector<std::string> argv;
1492 argv.push_back(patchoat);
1493 argv.push_back(isa_arg);
1494 argv.push_back(input_oat_filename_arg);
1495 argv.push_back(output_oat_filename_arg);
1496 argv.push_back(patched_image_arg);
1497
1498 std::string command_line(Join(argv, ' '));
1499 LOG(INFO) << "Relocate Oat File: " << command_line;
1500 bool success = Exec(argv, error_msg);
1501 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001502 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001503 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001504 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001505 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1506 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001507 return output.release();
1508 } else if (output.get() != nullptr) {
1509 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1510 "but output file '%s' failed verifcation: %s",
1511 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1512 } else {
1513 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1514 "but was unable to open output file '%s': %s",
1515 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1516 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001517 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001518 // patchoat failed which means we probably don't have enough room to place the output oat file,
1519 // instead of failing we should just run the interpreter from the dex files in the input oat.
1520 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1521 << "for interpretation. patchoat failure was: " << *error_msg;
1522 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001523 } else {
1524 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1525 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1526 error_msg->c_str());
1527 }
1528 return nullptr;
1529}
1530
Andreas Gampe7ba64962014-10-23 11:37:40 -07001531bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001532 bool* checksum_verified,
1533 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001534 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001535 if (image_space == nullptr) {
1536 *error_msg = "No image space present";
1537 return false;
1538 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001539 uint32_t real_image_checksum;
1540 void* real_image_oat_offset;
1541 int32_t real_patch_delta;
1542 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001543 const ImageHeader& image_header = image_space->GetImageHeader();
1544 real_image_checksum = image_header.GetOatChecksum();
1545 real_image_oat_offset = image_header.GetOatDataBegin();
1546 real_patch_delta = image_header.GetPatchDelta();
1547 } else {
1548 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1549 image_space->GetImageLocation().c_str(), isa));
1550 real_image_checksum = image_header->GetOatChecksum();
1551 real_image_oat_offset = image_header->GetOatDataBegin();
1552 real_patch_delta = image_header->GetPatchDelta();
1553 }
1554
1555 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001556 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001557
1558 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1559 *checksum_verified = oat_image_checksum == real_image_checksum;
1560 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001561 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1562 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001563 }
1564
Andreas Gampe7ba64962014-10-23 11:37:40 -07001565 bool offset_verified;
1566 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001567
Andreas Gampe7ba64962014-10-23 11:37:40 -07001568 if (!oat_file->IsPic()) {
1569 // If an oat file is not PIC, we need to check that the image is at the expected location and
1570 // patched in the same way.
1571 void* oat_image_oat_offset =
1572 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1573 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1574 if (!offset_verified) {
1575 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1576 real_image_oat_offset, oat_image_oat_offset);
1577 }
1578
1579 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1580 patch_delta_verified = oat_patch_delta == real_patch_delta;
1581 if (!patch_delta_verified) {
1582 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1583 "received 0x%x)", real_patch_delta, oat_patch_delta);
1584 }
1585 } else {
1586 // If an oat file is PIC, we ignore offset and patching delta.
1587 offset_verified = true;
1588 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001589 }
1590
1591 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001592 if (!ret) {
1593 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001594 }
1595 return ret;
1596}
1597
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001598const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1599 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001600 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001601 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001602 return oat_file;
1603 }
1604
Igor Murashkin46774762014-10-22 11:37:02 -07001605 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001606 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001607}
1608
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001609static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001610 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001611 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1612
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001613 DCHECK(obj != nullptr);
1614 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001615
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001616 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001617 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001618 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001619 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers848871b2013-08-05 10:56:33 -07001620 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001621 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1622 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001623 }
1624 }
1625 }
1626}
1627
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001628void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001629 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001630 CHECK(!init_done_);
1631
Mathieu Chartier590fee92013-09-13 13:46:47 -07001632 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001633 gc::Heap* heap = Runtime::Current()->GetHeap();
1634 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001635 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001636 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001637 OatFile& oat_file = GetImageOatFile(space);
1638 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1639 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001640 const char* image_file_location = oat_file.GetOatHeader().
1641 GetStoreValueByKey(OatHeader::kImageLocationKey);
1642 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001643 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1644 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001645 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1646 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001647 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001648 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001649 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1650 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1651 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001652
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001653 StackHandleScope<1> hs(self);
1654 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1655 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1656 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001657 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001658
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001659 // Special case of setting up the String class early so that we can test arbitrary objects
1660 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001661 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001662
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001663 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001664 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001665 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001666 StackHandleScope<1> hs2(self);
1667 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001668 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001669 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1670 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001671 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001672 std::string error_msg;
1673 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001674 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001675 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001676 << " from within oat file " << oat_file.GetLocation()
1677 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001678 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001679
1680 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1681
1682 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001683 }
1684
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001685 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1686 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001687 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001688
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001689 // Set entry point to interpreter if in InterpretOnly mode.
1690 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001691 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001692 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001693 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001694
1695 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001696 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001697 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001698
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001699 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001700 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1701 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001702 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001703 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001704 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001705 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1706 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1707 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1708 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1709 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1710 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1711 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1712 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1713 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1714 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001715
Ian Rogers98379392014-02-24 16:53:16 -08001716 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001717
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001718 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001719}
1720
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001721void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1722 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1723 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001724 for (GcRoot<mirror::Class>& root : class_table_) {
1725 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1726 }
1727 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1728 root.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001729 }
1730 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001731 for (auto& root : new_class_roots_) {
1732 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
1733 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1734 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001735 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001736 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1737 // corresponding object. This is slow, but luckily for us, this may only happen with a
1738 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001739 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
1740 class_table_.Erase(it);
1741 class_table_.Insert(GcRoot<mirror::Class>(new_ref));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001742 }
1743 }
1744 }
1745 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1746 new_class_roots_.clear();
1747 }
1748 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1749 log_new_class_table_roots_ = true;
1750 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1751 log_new_class_table_roots_ = false;
1752 }
1753 // We deliberately ignore the class roots in the image since we
1754 // handle image roots by using the MS/CMS rescanning of dirty cards.
1755}
1756
Brian Carlstroma663ea52011-08-19 23:33:41 -07001757// Keep in sync with InitCallback. Anything we visit, we need to
1758// reinit references to when reinitializing a ClassLinker from a
1759// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001760void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001761 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001762 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001763 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001764 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001765 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001766 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1767 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001768 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001769 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1770 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001771 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001772 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001773 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001774 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1775 new_dex_cache_roots_.clear();
1776 }
1777 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1778 log_new_dex_caches_roots_ = true;
1779 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1780 log_new_dex_caches_roots_ = false;
1781 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001782 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001783 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001784 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1785 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001786 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001787 if (!find_array_class_cache_[i].IsNull()) {
1788 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001789 }
1790 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001791}
1792
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001793void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1794 if (dex_cache_image_class_lookup_required_) {
1795 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001796 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001797 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001798 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001799 for (GcRoot<mirror::Class>& root : class_table_) {
1800 if (!visitor(root.Read(), arg)) {
1801 return;
1802 }
1803 }
1804 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1805 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001806 return;
1807 }
1808 }
1809}
1810
Ian Rogersdbf3be02014-08-29 15:40:08 -07001811static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001812 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001813 classes->insert(c);
1814 return true;
1815}
1816
Ian Rogersdbf3be02014-08-29 15:40:08 -07001817struct GetClassesVisitorArrayArg {
1818 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1819 int32_t index;
1820 bool success;
1821};
1822
1823static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1824 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1825 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1826 if (arg->index < (*arg->classes)->GetLength()) {
1827 (*arg->classes)->Set(arg->index, c);
1828 arg->index++;
1829 return true;
1830 } else {
1831 arg->success = false;
1832 return false;
1833 }
1834}
1835
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001836void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001837 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1838 // is avoiding duplicates.
1839 if (!kMovingClasses) {
1840 std::set<mirror::Class*> classes;
1841 VisitClasses(GetClassesVisitorSet, &classes);
1842 for (mirror::Class* klass : classes) {
1843 if (!visitor(klass, arg)) {
1844 return;
1845 }
1846 }
1847 } else {
1848 Thread* self = Thread::Current();
1849 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001850 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001851 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1852 GetClassesVisitorArrayArg local_arg;
1853 local_arg.classes = &classes;
1854 local_arg.success = false;
1855 // We size the array assuming classes won't be added to the class table during the visit.
1856 // If this assumption fails we iterate again.
1857 while (!local_arg.success) {
1858 size_t class_table_size;
1859 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001860 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001861 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001862 }
1863 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1864 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1865 classes.Assign(
1866 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1867 CHECK(classes.Get() != nullptr); // OOME.
1868 local_arg.index = 0;
1869 local_arg.success = true;
1870 VisitClasses(GetClassesVisitorArray, &local_arg);
1871 }
1872 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1873 // If the class table shrank during creation of the clases array we expect null elements. If
1874 // the class table grew then the loop repeats. If classes are created after the loop has
1875 // finished then we don't visit.
1876 mirror::Class* klass = classes->Get(i);
1877 if (klass != nullptr && !visitor(klass, arg)) {
1878 return;
1879 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001880 }
1881 }
1882}
1883
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001884ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001885 mirror::Class::ResetClass();
1886 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001887 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001888 mirror::ArtField::ResetClass();
1889 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001890 mirror::BooleanArray::ResetArrayClass();
1891 mirror::ByteArray::ResetArrayClass();
1892 mirror::CharArray::ResetArrayClass();
1893 mirror::DoubleArray::ResetArrayClass();
1894 mirror::FloatArray::ResetArrayClass();
1895 mirror::IntArray::ResetArrayClass();
1896 mirror::LongArray::ResetArrayClass();
1897 mirror::ShortArray::ResetArrayClass();
1898 mirror::Throwable::ResetClass();
1899 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001900 STLDeleteElements(&boot_class_path_);
1901 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001902}
1903
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001904mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001905 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001906 StackHandleScope<16> hs(self);
1907 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1908 Handle<mirror::DexCache> dex_cache(
1909 hs.NewHandle(down_cast<mirror::DexCache*>(
1910 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1911 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001912 if (dex_cache.Get() == nullptr) {
1913 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001914 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001915 Handle<mirror::String>
1916 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001917 if (location.Get() == nullptr) {
1918 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001919 }
Ian Rogers700a4022014-05-19 16:49:03 -07001920 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001921 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001922 if (strings.Get() == nullptr) {
1923 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001924 }
Ian Rogers700a4022014-05-19 16:49:03 -07001925 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001926 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001927 if (types.Get() == nullptr) {
1928 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001929 }
Ian Rogers700a4022014-05-19 16:49:03 -07001930 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001931 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001932 if (methods.Get() == nullptr) {
1933 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001934 }
Ian Rogers700a4022014-05-19 16:49:03 -07001935 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001936 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001937 if (fields.Get() == nullptr) {
1938 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001939 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001940 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1941 fields.Get());
1942 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001943}
1944
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001945mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001946 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001947 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001948 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001949 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001950 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001951 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1952 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001953 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001954 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001955 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001956 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001957 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001958}
1959
Ian Rogers6fac4472014-02-25 17:01:10 -08001960mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001961 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001962}
1963
Brian Carlstromea46f952013-07-30 01:26:50 -07001964mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001965 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001966 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001967}
1968
Brian Carlstromea46f952013-07-30 01:26:50 -07001969mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001970 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001971 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001972}
1973
Mathieu Chartier590fee92013-09-13 13:46:47 -07001974mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1975 Thread* self, size_t length) {
1976 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1977 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001978}
1979
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001980mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1981 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001982 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001983
1984 // For temporary classes we must wait for them to be retired.
1985 if (init_done_ && klass->IsTemp()) {
1986 CHECK(!klass->IsResolved());
1987 if (klass->IsErroneous()) {
1988 ThrowEarlierClassFailure(klass);
1989 return nullptr;
1990 }
1991 StackHandleScope<1> hs(self);
1992 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1993 ObjectLock<mirror::Class> lock(self, h_class);
1994 // Loop and wait for the resolving thread to retire this class.
1995 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1996 lock.WaitIgnoringInterrupts();
1997 }
1998 if (h_class->IsErroneous()) {
1999 ThrowEarlierClassFailure(h_class.Get());
2000 return nullptr;
2001 }
2002 CHECK(h_class->IsRetired());
2003 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002004 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2005 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002006 }
2007
Brian Carlstromaded5f72011-10-07 17:15:04 -07002008 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002009 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002010 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002011 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2012 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002013 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002014 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2015 ThrowClassCircularityError(h_class.Get());
2016 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002017 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002018 }
2019 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002020 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002021 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002022 }
2023 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002024
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002025 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002026 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002027 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002028 }
2029 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002030 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002031 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002032 return klass;
2033}
2034
Ian Rogers68b56852014-08-29 20:19:11 -07002035typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2036
2037// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002038ClassPathEntry FindInClassPath(const char* descriptor,
2039 size_t hash, const std::vector<const DexFile*>& class_path) {
2040 for (const DexFile* dex_file : class_path) {
2041 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002042 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002043 return ClassPathEntry(dex_file, dex_class_def);
2044 }
2045 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002046 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002047}
2048
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002049mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2050 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002051 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002052 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002053 if (class_loader->GetClass() !=
2054 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2055 class_loader->GetParent()->GetClass() !=
2056 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2057 return nullptr;
2058 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002059 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002060 // Check if this would be found in the parent boot class loader.
2061 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002062 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002063 if (klass != nullptr) {
2064 return EnsureResolved(self, descriptor, klass);
2065 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002066 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002067 *pair.second);
2068 if (klass != nullptr) {
2069 return klass;
2070 }
2071 CHECK(self->IsExceptionPending()) << descriptor;
2072 self->ClearException();
2073 } else {
2074 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2075 StackHandleScope<3> hs(self);
2076 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2077 // We need to get the DexPathList and loop through it.
2078 Handle<mirror::ArtField> cookie_field =
2079 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2080 Handle<mirror::ArtField> dex_file_field =
2081 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002082 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002083 mirror::Object* dex_path_list =
2084 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2085 GetObject(class_loader.Get());
2086 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2087 cookie_field.Get() != nullptr) {
2088 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2089 mirror::Object* dex_elements_obj =
2090 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2091 GetObject(dex_path_list);
2092 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2093 // at the mCookie which is a DexFile vector.
2094 if (dex_elements_obj != nullptr) {
2095 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2096 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2097 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2098 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2099 if (element == nullptr) {
2100 // Should never happen, fall back to java code to throw a NPE.
2101 break;
2102 }
2103 mirror::Object* dex_file = dex_file_field->GetObject(element);
2104 if (dex_file != nullptr) {
2105 const uint64_t cookie = cookie_field->GetLong(dex_file);
2106 auto* dex_files =
2107 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2108 if (dex_files == nullptr) {
2109 // This should never happen so log a warning.
2110 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2111 break;
2112 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002113 for (const DexFile* cp_dex_file : *dex_files) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002114 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002115 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002116 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002117 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2118 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002119 if (klass == nullptr) {
2120 CHECK(self->IsExceptionPending()) << descriptor;
2121 self->ClearException();
2122 return nullptr;
2123 }
2124 return klass;
2125 }
2126 }
2127 }
2128 }
2129 }
2130 }
2131 }
2132 return nullptr;
2133}
2134
Ian Rogers98379392014-02-24 16:53:16 -08002135mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002136 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002137 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002138 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002139 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002140 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002141 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2142 // for primitive classes that aren't backed by dex files.
2143 return FindPrimitiveClass(descriptor[0]);
2144 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002145 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002146 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002147 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002148 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002149 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002150 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002151 // Class is not yet loaded.
2152 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002153 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002154 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002155 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002156 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002157 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002158 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002159 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002160 } else {
2161 // The boot class loader is searched ahead of the application class loader, failures are
2162 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2163 // trigger the chaining with a proper stack trace.
2164 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2165 self->SetException(ThrowLocation(), pre_allocated);
2166 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002167 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002168 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002169 // First try with the bootstrap class loader.
2170 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002171 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002172 if (klass != nullptr) {
2173 return EnsureResolved(self, descriptor, klass);
2174 }
2175 }
Ian Rogers63557452014-06-04 16:57:15 -07002176 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2177 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002178 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002179 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002180 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002181 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002182 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002183 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002184 const std::vector<const DexFile*>* class_path;
2185 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002186 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002187 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002188 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002189 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2190 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002191 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002192 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002193 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002194 } else {
2195 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2196 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2197 self->SetException(ThrowLocation(), pre_allocated);
2198 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002199 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002200 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002201 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002202 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2203 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002204 if (cp_klass != nullptr) {
2205 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002206 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002207 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002208 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002209 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002210 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002211 {
2212 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002213 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2214 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002215 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002216 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002217 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002218 }
Ian Rogers68b56852014-08-29 20:19:11 -07002219 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002220 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2221 WellKnownClasses::java_lang_ClassLoader_loadClass,
2222 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002223 }
Ian Rogers98379392014-02-24 16:53:16 -08002224 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002225 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002226 return nullptr;
2227 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002228 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002229 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002230 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002231 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002232 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002233 // success, return mirror::Class*
2234 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002235 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002236 }
Ian Rogers07140832014-09-30 15:43:59 -07002237 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002238}
2239
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002240mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002241 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002242 const DexFile& dex_file,
2243 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002244 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002245 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002246
Brian Carlstromaded5f72011-10-07 17:15:04 -07002247 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002248 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002249 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002250 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002251 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002252 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002253 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002254 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002255 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002256 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2257 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002258 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002259 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002260 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002261 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002262 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002263 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002264 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002265 }
2266
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002267 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002268 // Allocate a class with the status of not ready.
2269 // Interface object should get the right size here. Regular class will
2270 // figure out the right size later and be replaced with one of the right
2271 // size when the class becomes resolved.
2272 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002273 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002274 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002275 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002276 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002277 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002278 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002279 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002280 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002281 if (self->IsExceptionPending()) {
2282 // An exception occured during load, set status to erroneous while holding klass' lock in case
2283 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002284 if (!klass->IsErroneous()) {
2285 klass->SetStatus(mirror::Class::kStatusError, self);
2286 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002287 return nullptr;
2288 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002289 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002290
Mathieu Chartier590fee92013-09-13 13:46:47 -07002291 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002292 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002293 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002294 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2295 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002296 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002297 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002298
Brian Carlstromaded5f72011-10-07 17:15:04 -07002299 // Finish loading (if necessary) by finding parents
2300 CHECK(!klass->IsLoaded());
2301 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2302 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002303 if (!klass->IsErroneous()) {
2304 klass->SetStatus(mirror::Class::kStatusError, self);
2305 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002306 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002307 }
2308 CHECK(klass->IsLoaded());
2309 // Link the class (if necessary)
2310 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002311 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002312 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002313
2314 mirror::Class* new_class = nullptr;
2315 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002316 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002317 if (!klass->IsErroneous()) {
2318 klass->SetStatus(mirror::Class::kStatusError, self);
2319 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002320 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002321 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002322 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002323 CHECK(new_class != nullptr) << descriptor;
2324 CHECK(new_class->IsResolved()) << descriptor;
2325
2326 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002327
2328 /*
2329 * We send CLASS_PREPARE events to the debugger from here. The
2330 * definition of "preparation" is creating the static fields for a
2331 * class and initializing them to the standard default values, but not
2332 * executing any code (that comes later, during "initialization").
2333 *
2334 * We did the static preparation in LinkClass.
2335 *
2336 * The class has been prepared and resolved but possibly not yet verified
2337 * at this point.
2338 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002339 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002340
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002341 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002342}
2343
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002344uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2345 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002346 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002347 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002348 size_t num_8 = 0;
2349 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002350 size_t num_32 = 0;
2351 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002352 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002353 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2354 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002355 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002356 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002357 switch (c) {
2358 case 'L':
2359 case '[':
2360 num_ref++;
2361 break;
2362 case 'J':
2363 case 'D':
2364 num_64++;
2365 break;
2366 case 'I':
2367 case 'F':
2368 num_32++;
2369 break;
2370 case 'S':
2371 case 'C':
2372 num_16++;
2373 break;
2374 case 'B':
2375 case 'Z':
2376 num_8++;
2377 break;
2378 default:
2379 LOG(FATAL) << "Unknown descriptor: " << c;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002380 }
2381 }
2382 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002383 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002384}
2385
Ian Rogers97b52f82014-08-14 11:34:07 -07002386OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2387 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002388 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002389 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2390 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002391 *found = false;
2392 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002393 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002394 *found = true;
2395 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002396}
2397
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002398static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2399 uint32_t method_idx) {
2400 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002401 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002402 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002403 ClassDataItemIterator it(dex_file, class_data);
2404 // Skip fields
2405 while (it.HasNextStaticField()) {
2406 it.Next();
2407 }
2408 while (it.HasNextInstanceField()) {
2409 it.Next();
2410 }
2411 // Process methods
2412 size_t class_def_method_index = 0;
2413 while (it.HasNextDirectMethod()) {
2414 if (it.GetMemberIndex() == method_idx) {
2415 return class_def_method_index;
2416 }
2417 class_def_method_index++;
2418 it.Next();
2419 }
2420 while (it.HasNextVirtualMethod()) {
2421 if (it.GetMemberIndex() == method_idx) {
2422 return class_def_method_index;
2423 }
2424 class_def_method_index++;
2425 it.Next();
2426 }
2427 DCHECK(!it.HasNext());
2428 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2429 return 0;
2430}
2431
Ian Rogers97b52f82014-08-14 11:34:07 -07002432const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002433 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002434 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002435 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002436 size_t oat_method_index;
2437 if (method->IsStatic() || method->IsDirect()) {
2438 // Simple case where the oat method index was stashed at load time.
2439 oat_method_index = method->GetMethodIndex();
2440 } else {
2441 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2442 // by search for its position in the declared virtual methods.
2443 oat_method_index = declaring_class->NumDirectMethods();
2444 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002445 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002446 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002447 // Check method index instead of identity in case of duplicate method definitions.
2448 if (method->GetDexMethodIndex() ==
2449 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002450 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002451 break;
2452 }
Ian Rogersf320b632012-03-13 18:47:47 -07002453 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002454 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002455 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2456 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002457 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002458 DCHECK_EQ(oat_method_index,
2459 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002460 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002461 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002462 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2463 declaring_class->GetDexClassDefIndex(),
2464 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002465 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002466 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002467 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002468 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002469}
2470
2471// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002472const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002473 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002474 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002475 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002476 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002477 bool found;
2478 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002479 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002480 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002481 result = oat_method.GetQuickCode();
2482 }
2483
Ian Rogersef7d42f2014-01-06 12:55:46 -08002484 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002485 if (method->IsNative()) {
2486 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002487 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002488 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002489 // No code? Do we expect portable code?
2490 result = GetQuickToPortableBridge();
2491 } else {
2492 // No code? You must mean to go into the interpreter.
2493 result = GetQuickToInterpreterBridge();
2494 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002495 }
2496 return result;
TDYa12785321912012-04-01 15:24:56 -07002497}
2498
Ian Rogersef7d42f2014-01-06 12:55:46 -08002499const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2500 bool* have_portable_code) {
2501 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2502 *have_portable_code = false;
2503 if (method->IsProxyMethod()) {
2504 return GetPortableProxyInvokeHandler();
2505 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002506 bool found;
2507 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002508 const void* result = nullptr;
2509 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002510 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002511 result = oat_method.GetPortableCode();
2512 quick_code = oat_method.GetQuickCode();
2513 }
2514
Ian Rogersef7d42f2014-01-06 12:55:46 -08002515 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002516 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002517 // No code? You must mean to go into the interpreter.
2518 result = GetPortableToInterpreterBridge();
2519 } else {
2520 // No code? But there's quick code, so use a bridge.
2521 result = GetPortableToQuickBridge();
2522 }
2523 } else {
2524 *have_portable_code = true;
2525 }
2526 return result;
2527}
2528
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002529const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2530 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2531 return nullptr;
2532 }
2533 bool found;
2534 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2535 return found ? oat_method.GetQuickCode() : nullptr;
2536}
2537
2538const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2539 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2540 return nullptr;
2541 }
2542 bool found;
2543 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2544 return found ? oat_method.GetPortableCode() : nullptr;
2545}
2546
Ian Rogersef7d42f2014-01-06 12:55:46 -08002547const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2548 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002549 bool found;
2550 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2551 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002552 return nullptr;
2553 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002554 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002555 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002556}
2557
2558const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2559 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002560 bool found;
2561 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2562 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002563 return nullptr;
2564 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002565 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002566 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002567}
2568
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002569// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002570static bool NeedsInterpreter(
2571 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2572 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002573 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002574 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002575 // May return true for native code, in the case of generic JNI
2576 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002577 return true;
2578 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002579#ifdef ART_SEA_IR_MODE
2580 ScopedObjectAccess soa(Thread::Current());
2581 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2582 LOG(INFO) << "Found " << PrettyMethod(method);
2583 return false;
2584 }
2585#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002586 // If interpreter mode is enabled, every method (except native and proxy) must
2587 // be run with interpreter.
2588 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2589 !method->IsNative() && !method->IsProxyMethod();
2590}
2591
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002592void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002593 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002594 if (klass->NumDirectMethods() == 0) {
2595 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002596 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002597 Runtime* runtime = Runtime::Current();
2598 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002599 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2600 return; // OAT file unavailable.
2601 }
Ian Rogers19846512012-02-24 11:42:47 -08002602 }
Alex Light64ad14d2014-08-19 14:23:13 -07002603
Mathieu Chartierf8322842014-05-16 10:59:25 -07002604 const DexFile& dex_file = klass->GetDexFile();
2605 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002606 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002607 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002608 // There should always be class data if there were direct methods.
2609 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002610 ClassDataItemIterator it(dex_file, class_data);
2611 // Skip fields
2612 while (it.HasNextStaticField()) {
2613 it.Next();
2614 }
2615 while (it.HasNextInstanceField()) {
2616 it.Next();
2617 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002618 bool has_oat_class;
2619 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2620 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002621 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002622 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002623 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002624 if (!method->IsStatic()) {
2625 // Only update static methods.
2626 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002627 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002628 const void* portable_code = nullptr;
2629 const void* quick_code = nullptr;
2630 if (has_oat_class) {
2631 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2632 portable_code = oat_method.GetPortableCode();
2633 quick_code = oat_method.GetQuickCode();
2634 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002635 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2636 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002637 if (enter_interpreter) {
2638 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002639 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002640 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002641 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002642 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002643 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002644 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002645 quick_code = GetQuickToInterpreterBridge();
2646 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002647 } else {
2648 if (portable_code == nullptr) {
2649 portable_code = GetPortableToQuickBridge();
2650 } else {
2651 have_portable_code = true;
2652 }
2653 if (quick_code == nullptr) {
2654 quick_code = GetQuickToPortableBridge();
2655 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002656 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002657 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2658 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002659 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002660 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002661}
2662
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002663void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002664 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002665 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002666 Runtime* runtime = Runtime::Current();
2667 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002668 // The following code only applies to a non-compiler runtime.
2669 return;
2670 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002671 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002672 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2673 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002674 if (oat_class != nullptr) {
2675 // Every kind of method should at least get an invoke stub from the oat_method.
2676 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002677 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002678 oat_method.LinkMethod(method.Get());
2679 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002680
Jeff Hao16743632013-05-08 10:59:04 -07002681 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002682 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002683 method->GetEntryPointFromQuickCompiledCode(),
2684 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002685 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002686 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002687 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002688 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002689 }
2690
Brian Carlstrom92827a52011-10-10 15:50:01 -07002691 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002692 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2693 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002694 return;
2695 }
Ian Rogers19846512012-02-24 11:42:47 -08002696
Ian Rogersef7d42f2014-01-06 12:55:46 -08002697 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002698 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002699 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002700 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2701 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002702 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2703 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002704 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002705 if (!method->IsNative()) {
2706 // Set entry point from compiled code if there's no code or in interpreter only mode.
2707 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2708 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2709 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002710 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002711 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2712 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002713 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2714 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2715 have_portable_code = true;
2716 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2717 } else {
2718 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2719 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002720 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002721
Ian Rogers62d6c772013-02-27 08:32:07 -08002722 if (method->IsNative()) {
2723 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002724 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002725
2726 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002727 // We have a native method here without code. Then it should have either the generic JNI
2728 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2729 // TODO: this doesn't handle all the cases where trampolines may be installed.
2730 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2731 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002732 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002733 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002734
Ian Rogers62d6c772013-02-27 08:32:07 -08002735 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002736 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002737 method->GetEntryPointFromQuickCompiledCode(),
2738 method->GetEntryPointFromPortableCompiledCode(),
2739 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002740}
2741
Fred Shih37f05ef2014-07-16 18:38:08 -07002742
Fred Shih37f05ef2014-07-16 18:38:08 -07002743
Ian Rogers7b078e82014-09-10 14:44:24 -07002744void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002745 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002746 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002747 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002748 CHECK(klass.Get() != nullptr);
2749 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002750 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002751 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002752 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002753
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002754 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002755 if (kUseBakerOrBrooksReadBarrier) {
2756 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002757 }
Andreas Gampe51829322014-08-25 15:05:04 -07002758 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002759 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002760 klass->SetAccessFlags(access_flags);
2761 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002762 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002763 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002764
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002765 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002766 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002767
Ian Rogers13735952014-10-08 12:43:28 -07002768 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002769 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002770 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002771 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002772
Ian Rogers97b52f82014-08-14 11:34:07 -07002773
2774 bool has_oat_class = false;
2775 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2776 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2777 &has_oat_class);
2778 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002779 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002780 }
2781 }
2782 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002783 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002784 }
2785}
2786
Ian Rogers7b078e82014-09-10 14:44:24 -07002787void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002788 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002789 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002790 const OatFile::OatClass* oat_class) {
2791 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002792 ClassDataItemIterator it(dex_file, class_data);
2793 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002794 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002795 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002796 CHECK(self->IsExceptionPending()); // OOME.
2797 return;
2798 }
2799 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002800 }
2801 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002802 mirror::ObjectArray<mirror::ArtField>* fields =
2803 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002804 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002805 CHECK(self->IsExceptionPending()); // OOME.
2806 return;
2807 }
2808 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002809 }
2810 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002811 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002812 StackHandleScope<1> hs(self);
2813 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002814 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002815 CHECK(self->IsExceptionPending()); // OOME.
2816 return;
2817 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002818 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002819 LoadField(dex_file, it, klass, sfield);
2820 }
2821 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002822 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002823 StackHandleScope<1> hs(self);
2824 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002825 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002826 CHECK(self->IsExceptionPending()); // OOME.
2827 return;
2828 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002829 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002830 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002831 }
2832
Ian Rogers0571d352011-11-03 19:51:38 -07002833 // Load methods.
2834 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002835 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002836 mirror::ObjectArray<mirror::ArtMethod>* directs =
2837 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002838 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002839 CHECK(self->IsExceptionPending()); // OOME.
2840 return;
2841 }
2842 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002843 }
Ian Rogers0571d352011-11-03 19:51:38 -07002844 if (it.NumVirtualMethods() != 0) {
2845 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002846 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2847 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002848 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002849 CHECK(self->IsExceptionPending()); // OOME.
2850 return;
2851 }
2852 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002853 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002854 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002855 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2856 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002857 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002858 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002859 StackHandleScope<1> hs(self);
2860 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002861 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002862 CHECK(self->IsExceptionPending()); // OOME.
2863 return;
2864 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002865 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002866 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002867 uint32_t it_method_index = it.GetMemberIndex();
2868 if (last_dex_method_index == it_method_index) {
2869 // duplicate case
2870 method->SetMethodIndex(last_class_def_method_index);
2871 } else {
2872 method->SetMethodIndex(class_def_method_index);
2873 last_dex_method_index = it_method_index;
2874 last_class_def_method_index = class_def_method_index;
2875 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002876 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002877 }
2878 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002879 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002880 StackHandleScope<1> hs(self);
2881 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002882 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002883 CHECK(self->IsExceptionPending()); // OOME.
2884 return;
2885 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002886 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002887 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002888 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002889 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002890 }
2891 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002892}
2893
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002894void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002895 Handle<mirror::Class> klass,
2896 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002897 uint32_t field_idx = it.GetMemberIndex();
2898 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002899 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002900 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002901}
2902
Brian Carlstromea46f952013-07-30 01:26:50 -07002903mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002904 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002905 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002906 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002907 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002908 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002909
Brian Carlstromea46f952013-07-30 01:26:50 -07002910 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002911 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002912 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002913 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002914 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002915 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002916
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002917 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002918 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002919 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002920 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002921
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002922 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002923 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002924 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002925
Andreas Gampe51829322014-08-25 15:05:04 -07002926 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002927
Ian Rogersdfb325e2013-10-30 01:00:44 -07002928 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002929 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002930 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2931 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002932 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002933 klass->SetFinalizable();
2934 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002935 std::string temp;
2936 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002937 // The Enum class declares a "final" finalize() method to prevent subclasses from
2938 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2939 // subclasses, so we exclude it here.
2940 // We also want to avoid setting the flag on Object, where we know that finalize() is
2941 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002942 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2943 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002944 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002945 }
2946 }
2947 }
2948 } else if (method_name[0] == '<') {
2949 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002950 bool is_init = (strcmp("<init>", method_name) == 0);
2951 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002952 if (UNLIKELY(!is_init && !is_clinit)) {
2953 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2954 } else {
2955 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2956 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002957 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002958 access_flags |= kAccConstructor;
2959 }
2960 }
2961 }
2962 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002963
Mathieu Chartier66f19252012-09-18 08:57:04 -07002964 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002965}
2966
Ian Rogers7b078e82014-09-10 14:44:24 -07002967void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002968 StackHandleScope<1> hs(self);
2969 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002970 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2971 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002972 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002973}
2974
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002975void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002976 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002977 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002978 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002979 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002980}
2981
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002982bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002983 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002984 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002985 mirror::DexCache* dex_cache = GetDexCache(i);
2986 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002987 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002988 }
2989 }
2990 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002991}
2992
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002993bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002994 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002995 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002996}
2997
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002998void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002999 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003000 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003001 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003002 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3003 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003004 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003005 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003006 if (log_new_dex_caches_roots_) {
3007 // TODO: This is not safe if we can remove dex caches.
3008 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3009 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003010}
3011
Brian Carlstromaded5f72011-10-07 17:15:04 -07003012void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003013 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003014 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003015 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003016 if (IsDexFileRegisteredLocked(dex_file)) {
3017 return;
3018 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003019 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003020 // Don't alloc while holding the lock, since allocation may need to
3021 // suspend all threads and another thread may need the dex_lock_ to
3022 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003023 StackHandleScope<1> hs(self);
3024 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003025 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3026 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003027 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003028 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003029 if (IsDexFileRegisteredLocked(dex_file)) {
3030 return;
3031 }
3032 RegisterDexFileLocked(dex_file, dex_cache);
3033 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003034}
3035
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003036void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003037 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003038 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003039 RegisterDexFileLocked(dex_file, dex_cache);
3040}
3041
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003042mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003043 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003044 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003045 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003046 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003047 if (dex_cache->GetDexFile() == &dex_file) {
3048 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003049 }
3050 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003051 // Search matching by location name.
3052 std::string location(dex_file.GetLocation());
3053 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003054 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003055 if (dex_cache->GetDexFile()->GetLocation() == location) {
3056 return dex_cache;
3057 }
3058 }
3059 // Failure, dump diagnostic and abort.
3060 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003061 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003062 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3063 }
3064 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003065 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003066}
3067
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003068void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003069 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003070 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003071 mirror::DexCache* dex_cache = GetDexCache(i);
3072 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003073 }
3074}
3075
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003076mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003077 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003078 if (UNLIKELY(klass == nullptr)) {
3079 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003080 }
3081 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003082}
3083
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003084mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3085 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003086 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003087 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003088 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003089 StackHandleScope<1> hs(self);
3090 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003091 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003092 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003093 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003094 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3095 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003096 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3097 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003098 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003099 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003100}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003101
Brian Carlstrombe977852011-07-19 14:54:54 -07003102// Create an array class (i.e. the class object for the array, not the
3103// array itself). "descriptor" looks like "[C" or "[[[[B" or
3104// "[Ljava/lang/String;".
3105//
3106// If "descriptor" refers to an array of primitives, look up the
3107// primitive type's internally-generated class object.
3108//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003109// "class_loader" is the class loader of the class that's referring to
3110// us. It's used to ensure that we're looking for the element type in
3111// the right context. It does NOT become the class loader for the
3112// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003113//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003114// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003115mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003116 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003117 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003118 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003119 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003120 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3121 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003122 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003123 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003124 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003125 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3126 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003127 if (component_type.Get() == nullptr) {
3128 DCHECK(self->IsExceptionPending());
3129 return nullptr;
3130 } else {
3131 self->ClearException();
3132 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003133 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003134 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3135 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3136 return nullptr;
3137 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003138 // See if the component type is already loaded. Array classes are
3139 // always associated with the class loader of their underlying
3140 // element type -- an array of Strings goes with the loader for
3141 // java/lang/String -- so we need to look for it there. (The
3142 // caller should have checked for the existence of the class
3143 // before calling here, but they did so with *their* class loader,
3144 // not the component type's loader.)
3145 //
3146 // If we find it, the caller adds "loader" to the class' initiating
3147 // loader list, which should prevent us from going through this again.
3148 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003149 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003150 // are the same, because our caller (FindClass) just did the
3151 // lookup. (Even if we get this wrong we still have correct behavior,
3152 // because we effectively do this lookup again when we add the new
3153 // class to the hash table --- necessary because of possible races with
3154 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003155 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003156 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003157 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003158 return new_class;
3159 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003160 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003161
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003162 // Fill out the fields in the Class.
3163 //
3164 // It is possible to execute some methods against arrays, because
3165 // all arrays are subclasses of java_lang_Object_, so we need to set
3166 // up a vtable. We can just point at the one in java_lang_Object_.
3167 //
3168 // Array classes are simple enough that we don't need to do a full
3169 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003170 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003171 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003172 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003173 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003174 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003175 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003176 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003177 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003178 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003179 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003180 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003181 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003182 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003183 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003184 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003185 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003186 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003187 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003188 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003189 }
3190 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003191 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003192 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003193 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003194 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003195 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003196 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003197 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003198 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003199 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003200 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003201 new_class->SetSuperClass(java_lang_Object);
3202 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003203 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003204 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003205 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003206 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003207 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3208 Runtime::Current()->GetImtUnimplementedMethod());
3209 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003210 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003211 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003212 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003213 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003214
3215
3216 // All arrays have java/lang/Cloneable and java/io/Serializable as
3217 // interfaces. We need to set that up here, so that stuff like
3218 // "instanceof" works right.
3219 //
3220 // Note: The GC could run during the call to FindSystemClass,
3221 // so we need to make sure the class object is GC-valid while we're in
3222 // there. Do this by clearing the interface list so the GC will just
3223 // think that the entries are null.
3224
3225
3226 // Use the single, global copies of "interfaces" and "iftable"
3227 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003228 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003229 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003230 CHECK(array_iftable != nullptr);
3231 new_class->SetIfTable(array_iftable);
3232 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003233
Elliott Hughes00626c22013-06-14 15:04:14 -07003234 // Inherit access flags from the component type.
3235 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3236 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3237 access_flags &= kAccJavaFlagsMask;
3238 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003239 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003240 access_flags |= kAccAbstract | kAccFinal;
3241 access_flags &= ~kAccInterface;
3242
3243 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003244
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003245 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003246 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003247 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003248 }
3249 // Another thread must have loaded the class after we
3250 // started but before we finished. Abandon what we've
3251 // done.
3252 //
3253 // (Yes, this happens.)
3254
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003255 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003256}
3257
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003258mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003259 switch (type) {
3260 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003261 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003262 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003263 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003264 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003265 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003266 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003267 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003268 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003269 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003270 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003271 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003272 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003273 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003274 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003275 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003276 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003277 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003278 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003279 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003280 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003281 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003282 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003283 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003284}
3285
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003286mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3287 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003288 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003289 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003290 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003291 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003292 source += " from ";
3293 source += dex_cache->GetLocation()->ToModifiedUtf8();
3294 }
3295 LOG(INFO) << "Loaded class " << descriptor << source;
3296 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003297 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003298 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003299 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003300 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003301 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003302 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003303 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003304 // Check a class loaded with the system class loader matches one in the image if the class
3305 // is in the image.
3306 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003307 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003308 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003309 }
3310 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003311 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003312 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003313 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003314 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003315 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003316 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003317}
3318
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003319mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3320 size_t hash) {
3321 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003322 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3323 hash);
3324 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003325 CHECK(klass->IsProxyClass());
3326 return nullptr;
3327 }
3328
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003329 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003330 CHECK_NE(existing, klass) << descriptor;
3331 CHECK(!existing->IsResolved()) << descriptor;
3332 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3333
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003334 CHECK(!klass->IsTemp()) << descriptor;
3335 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3336 dex_cache_image_class_lookup_required_) {
3337 // Check a class loaded with the system class loader matches one in the image if the class
3338 // is in the image.
3339 existing = LookupClassFromImage(descriptor);
3340 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003341 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003342 }
3343 }
3344 VerifyObject(klass);
3345
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003346 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003347 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003348 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003349 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003350 }
3351
3352 return existing;
3353}
3354
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003355bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003356 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003357 auto pair = std::make_pair(descriptor, class_loader);
3358 auto it = class_table_.Find(pair);
3359 if (it != class_table_.end()) {
3360 class_table_.Erase(it);
3361 return true;
3362 }
3363 it = pre_zygote_class_table_.Find(pair);
3364 if (it != pre_zygote_class_table_.end()) {
3365 pre_zygote_class_table_.Erase(it);
3366 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003367 }
3368 return false;
3369}
3370
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003371mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003372 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003373 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003374 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003375 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003376 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003377 return result;
3378 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003379 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003380 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3381 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003382 } else {
3383 // Lookup failed but need to search dex_caches_.
3384 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003385 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003386 InsertClass(descriptor, result, hash);
3387 } else {
3388 // Searching the image dex files/caches failed, we don't want to get into this situation
3389 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3390 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003391 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003392 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3393 MoveImageClassesToClassTable();
3394 }
3395 }
3396 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003397 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003398}
3399
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003400mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003401 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003402 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003403 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3404 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3405 if (it == pre_zygote_class_table_.end()) {
3406 it = class_table_.FindWithHash(descriptor_pair, hash);
3407 if (it == class_table_.end()) {
3408 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003409 }
3410 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003411 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003412}
3413
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003414static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3415 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3416 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003417 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003418 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3419 return root->AsObjectArray<mirror::DexCache>();
3420}
3421
3422void ClassLinker::MoveImageClassesToClassTable() {
3423 Thread* self = Thread::Current();
3424 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3425 if (!dex_cache_image_class_lookup_required_) {
3426 return; // All dex cache classes are already in the class table.
3427 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003428 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003429 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003430 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003431 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3432 mirror::DexCache* dex_cache = dex_caches->Get(i);
3433 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3434 for (int32_t j = 0; j < types->GetLength(); j++) {
3435 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003436 if (klass != nullptr) {
3437 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003438 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003439 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003440 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3441 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003442 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003443 << PrettyClassAndClassLoader(klass);
3444 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003445 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003446 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003447 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003448 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003449 }
3450 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003451 }
3452 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003453 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003454}
3455
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003456void ClassLinker::MoveClassTableToPreZygote() {
3457 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3458 DCHECK(pre_zygote_class_table_.Empty());
3459 pre_zygote_class_table_ = std::move(class_table_);
3460 class_table_.Clear();
3461}
3462
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003463mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003464 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003465 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3466 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3467 mirror::DexCache* dex_cache = dex_caches->Get(i);
3468 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003469 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003470 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003471 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003472 const DexFile::TypeId* type_id =
3473 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003474 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003475 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3476 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003477 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003478 return klass;
3479 }
3480 }
3481 }
3482 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003483 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003484}
3485
3486void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3487 result.clear();
3488 if (dex_cache_image_class_lookup_required_) {
3489 MoveImageClassesToClassTable();
3490 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003491 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3492 while (true) {
3493 auto it = class_table_.Find(descriptor);
3494 if (it == class_table_.end()) {
3495 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003496 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003497 result.push_back(it->Read());
3498 class_table_.Erase(it);
3499 }
3500 for (mirror::Class* k : result) {
3501 class_table_.Insert(GcRoot<mirror::Class>(k));
3502 }
3503 size_t pre_zygote_start = result.size();
3504 // Now handle the pre zygote table.
3505 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3506 // called from the debugger.
3507 while (true) {
3508 auto it = pre_zygote_class_table_.Find(descriptor);
3509 if (it == pre_zygote_class_table_.end()) {
3510 break;
3511 }
3512 result.push_back(it->Read());
3513 pre_zygote_class_table_.Erase(it);
3514 }
3515 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3516 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003517 }
3518}
3519
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003520void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003521 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003522 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003523
Ian Rogers9ffb0392012-09-10 11:56:50 -07003524 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003525 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003526 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003527 return;
3528 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003529 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3530 return;
3531 }
jeffhao98eacac2011-09-14 16:11:53 -07003532
Ian Rogers9ffb0392012-09-10 11:56:50 -07003533 // The class might already be erroneous, for example at compile time if we attempted to verify
3534 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003535 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003536 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003537 return;
3538 }
3539
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003540 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003541 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003542 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003543 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003544 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003545 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003546 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003547 }
jeffhao98eacac2011-09-14 16:11:53 -07003548
Jeff Hao4a200f52014-04-01 14:58:49 -07003549 // Skip verification if disabled.
3550 if (!Runtime::Current()->IsVerificationEnabled()) {
3551 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003552 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003553 return;
3554 }
3555
Ian Rogers9ffb0392012-09-10 11:56:50 -07003556 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003557 StackHandleScope<2> hs(self);
3558 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003559 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003560 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003561 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003562
3563 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003564 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003565 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003566 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003567 std::string error_msg(
3568 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3569 PrettyDescriptor(klass.Get()).c_str(),
3570 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003571 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003572 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3573 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003574 self->ClearException();
3575 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003576 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3577 if (cause.Get() != nullptr) {
3578 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003579 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003580 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003581 if (Runtime::Current()->IsCompiler()) {
3582 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3583 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003584 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003585 return;
3586 }
3587 }
3588
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003589 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003590 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003591 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003592 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003593 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003594 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003595 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003596 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003597 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3598 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003599 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003600 return;
3601 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003602 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003603 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003604 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003605 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003606 Runtime::Current()->IsCompiler(),
3607 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003608 }
3609 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003610 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003611 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003612 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3613 << " because: " << error_msg;
3614 }
Ian Rogers1f539342012-10-03 21:09:42 -07003615 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003616 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003617 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003618 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003619 // Even though there were no verifier failures we need to respect whether the super-class
3620 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003621 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003622 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003623 } else {
3624 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003625 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003626 // Pretend a soft failure occured so that we don't consider the class verified below.
3627 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003628 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003629 } else {
3630 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3631 // Soft failures at compile time should be retried at runtime. Soft
3632 // failures at runtime will be handled by slow paths in the generated
3633 // code. Set status accordingly.
3634 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003635 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003636 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003637 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003638 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3639 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003640 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003641 }
3642 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003643 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003644 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003645 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3646 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003647 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003648 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003649 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003650 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003651 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003652 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003653 // Let the interpreter know it by setting the kAccPreverified flag onto each
3654 // method.
3655 // Note: we're going here during compilation and at runtime. When we set the
3656 // kAccPreverified flag when compiling image classes, the flag is recorded
3657 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003658 EnsurePreverifiedMethods(klass);
3659 }
3660}
3661
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003662void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003663 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003664 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003665 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003666 }
jeffhao98eacac2011-09-14 16:11:53 -07003667}
3668
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003669bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3670 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003671 // If we're compiling, we can only verify the class using the oat file if
3672 // we are not compiling the image or if the class we're verifying is not part of
3673 // the app. In other words, we will only check for preverification of bootclasspath
3674 // classes.
3675 if (Runtime::Current()->IsCompiler()) {
3676 // Are we compiling the bootclasspath?
3677 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3678 return false;
3679 }
3680 // We are compiling an app (not the image).
3681
3682 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003683 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003684 return false;
3685 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003686 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003687
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003688 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003689 // In case we run without an image there won't be a backing oat file.
3690 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003691 return false;
3692 }
3693
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003694 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003695 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003696 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3697 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003698 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003699 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003700 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003701 // Compile time verification failed with a soft error. Compile time verification can fail
3702 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003703 // class ... {
3704 // Foo x;
3705 // .... () {
3706 // if (...) {
3707 // v1 gets assigned a type of resolved class Foo
3708 // } else {
3709 // v1 gets assigned a type of unresolved class Bar
3710 // }
3711 // iput x = v1
3712 // } }
3713 // when we merge v1 following the if-the-else it results in Conflict
3714 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3715 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3716 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3717 // at compile time).
3718 return false;
3719 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003720 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003721 // Compile time verification failed with a hard error. This is caused by invalid instructions
3722 // in the class. These errors are unrecoverable.
3723 return false;
3724 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003725 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003726 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3727 // not loading the class.
3728 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3729 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003730 return false;
3731 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003732 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003733 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003734 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003735 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003736
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003737 return false;
3738}
3739
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003740void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003741 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003742 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3743 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3744 }
3745 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3746 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3747 }
3748}
3749
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003750void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003751 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003752 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3753 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003754 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003755 return; // native or abstract method
3756 }
3757 if (code_item->tries_size_ == 0) {
3758 return; // nothing to process
3759 }
Ian Rogers13735952014-10-08 12:43:28 -07003760 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003761 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3762 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3763 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3764 CatchHandlerIterator iterator(handlers_ptr);
3765 for (; iterator.HasNext(); iterator.Next()) {
3766 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3767 // unresolved exception types will be ignored by exception delivery
3768 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003769 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003770 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003771 DCHECK(Thread::Current()->IsExceptionPending());
3772 Thread::Current()->ClearException();
3773 }
3774 }
3775 }
3776 handlers_ptr = iterator.EndDataPointer();
3777 }
3778}
3779
Brian Carlstromea46f952013-07-30 01:26:50 -07003780static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003781static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3782 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003783
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003784mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003785 jobjectArray interfaces, jobject loader,
3786 jobjectArray methods, jobjectArray throws) {
3787 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003788 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003789 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003790 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003791 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003792 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003793 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003794 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003795 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003796 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003797 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3798 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003799 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003800 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003801 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003802 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003803 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003804 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003805
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003806 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003807 {
3808 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003809 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003810 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003811 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003812 }
3813 klass->SetSFields(sfields);
3814 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003815 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3816 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003817 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3818 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003819 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003820 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003821 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003822 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003823 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003824 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003825 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3826 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003827 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3828 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003829 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003830 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003831 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003832 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003833 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003834 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003835 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003836
Ian Rogers466bb252011-10-14 03:29:56 -07003837 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003838 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003839 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003840 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003841 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003842 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003843 }
3844 klass->SetDirectMethods(directs);
3845 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003846 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003847 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003848 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003849 }
3850 klass->SetDirectMethod(0, constructor);
3851 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003852
Mathieu Chartier590fee92013-09-13 13:46:47 -07003853 // Create virtual method using specified prototypes.
3854 size_t num_virtual_methods =
3855 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003856 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003857 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3858 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003859 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003860 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003861 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003862 }
3863 klass->SetVirtualMethods(virtuals);
3864 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003865 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003866 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003867 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3868 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003869 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003870 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003871 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003872 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003873 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003874 }
3875 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003876 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003877
3878 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003879 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003880 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003881
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003882 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3883 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003884 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003885 // Must hold lock on object when resolved.
3886 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003887 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003888 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003889 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003890 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003891 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003892 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003893 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003894 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003895
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003896 CHECK(klass->IsRetired());
3897 CHECK_NE(klass.Get(), new_class);
3898 klass.Assign(new_class);
3899
3900 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003901 interfaces_sfield->SetObject<false>(klass.Get(),
3902 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003903 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003904 throws_sfield->SetObject<false>(klass.Get(),
3905 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003906
3907 {
3908 // Lock on klass is released. Lock new class object.
3909 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003910 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003911 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003912
3913 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003914 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003915 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003916 CheckProxyConstructor(klass->GetDirectMethod(0));
3917 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003918 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003919 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3920 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003921 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3922 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003923 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003924 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003925
Mathieu Chartier590fee92013-09-13 13:46:47 -07003926 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003927 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003928 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003929 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3930
3931 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003932 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003933 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003934
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003935 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003936 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003937 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003938 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003939 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003940 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3941 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003942 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003943 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003944}
3945
Ian Rogersef7d42f2014-01-06 12:55:46 -08003946std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003947 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003948 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003949 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003950 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3951}
3952
Ian Rogersef7d42f2014-01-06 12:55:46 -08003953mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3954 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003955 DCHECK(proxy_class->IsProxyClass());
3956 DCHECK(proxy_method->IsProxyMethod());
3957 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003958 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003959 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003960 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003961 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003962 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003963 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003964 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003965 break;
3966 }
3967 }
3968 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003969 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003970 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003971 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003972 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003973 return resolved_method;
3974}
3975
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003976
Brian Carlstromea46f952013-07-30 01:26:50 -07003977mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003978 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003979 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003980 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003981 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003982 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003983 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3984 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003985 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3986 // constructor method.
3987 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3988 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003989 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3990 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003991 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3992 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003993 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003994 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003995 }
Ian Rogers466bb252011-10-14 03:29:56 -07003996 // Make this constructor public and fix the class to be our Proxy version
3997 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003998 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003999 return constructor;
4000}
4001
Brian Carlstromea46f952013-07-30 01:26:50 -07004002static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004003 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004004 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004005 CHECK_STREQ(constructor->GetName(), "<init>");
4006 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4007 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004008 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004009}
4010
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004011mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004012 Handle<mirror::Class> klass,
4013 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004014 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4015 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004016 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004017 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004018 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004019 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004020 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004021 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004022 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004023 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004024 }
Ian Rogers466bb252011-10-14 03:29:56 -07004025
4026 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4027 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004028 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004029 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004030
Ian Rogers466bb252011-10-14 03:29:56 -07004031 // At runtime the method looks like a reference and argument saving method, clone the code
4032 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004033 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4034 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004035 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004036
Ian Rogersc2b44472011-12-14 21:17:17 -08004037 return method;
4038}
Jesse Wilson95caa792011-10-12 18:14:17 -04004039
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004040static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4041 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004042 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004043 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004044 CHECK(!prototype->IsFinal());
4045 CHECK(method->IsFinal());
4046 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004047
4048 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4049 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4050 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004051 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4052 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004053 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4054
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004055 CHECK_STREQ(method->GetName(), prototype->GetName());
4056 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004057 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004058 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004059}
4060
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004061static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4062 bool can_init_parents)
4063 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004064 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004065 return true;
4066 }
4067 if (!can_init_statics) {
4068 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004069 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004070 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004071 return false;
4072 }
4073 // Check if there are encoded static values needing initialization.
4074 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004075 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004076 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004077 if (dex_class_def->static_values_off_ != 0) {
4078 return false;
4079 }
4080 }
4081 }
4082 if (!klass->IsInterface() && klass->HasSuperClass()) {
4083 mirror::Class* super_class = klass->GetSuperClass();
4084 if (!can_init_parents && !super_class->IsInitialized()) {
4085 return false;
4086 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004087 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004088 return false;
4089 }
4090 }
4091 }
4092 return true;
4093}
4094
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004095bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004096 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004097 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4098
4099 // Are we already initialized and therefore done?
4100 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4101 // an initialized class will never change its state.
4102 if (klass->IsInitialized()) {
4103 return true;
4104 }
4105
4106 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004107 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004108 return false;
4109 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004110
Ian Rogers7b078e82014-09-10 14:44:24 -07004111 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004112 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004113 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004114 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004115
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004116 // Re-check under the lock in case another thread initialized ahead of us.
4117 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004118 return true;
4119 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004120
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004121 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004122 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004123 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004124 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004125 return false;
4126 }
4127
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004128 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004129
4130 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004131 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004132 if (!klass->IsVerified()) {
4133 // We failed to verify, expect either the klass to be erroneous or verification failed at
4134 // compile time.
4135 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004136 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004137 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004138 } else {
4139 CHECK(Runtime::Current()->IsCompiler());
4140 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004141 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004142 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004143 } else {
4144 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004145 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004146 }
4147
Brian Carlstromd1422f82011-09-28 11:37:09 -07004148 // If the class is kStatusInitializing, either this thread is
4149 // initializing higher up the stack or another thread has beat us
4150 // to initializing and we need to wait. Either way, this
4151 // invocation of InitializeClass will not be responsible for
4152 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004153 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004154 // Could have got an exception during verification.
4155 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004156 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004157 return false;
4158 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004159 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004160 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004161 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004162 return true;
4163 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004164 // No. That's fine. Wait for another thread to finish initializing.
4165 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004166 }
4167
4168 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004169 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004170 return false;
4171 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004172 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004173
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004174 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004175
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004176 // From here out other threads may observe that we're initializing and so changes of state
4177 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004178 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004179 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004180
4181 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004182 }
4183
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004184 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004185 if (!klass->IsInterface() && klass->HasSuperClass()) {
4186 mirror::Class* super_class = klass->GetSuperClass();
4187 if (!super_class->IsInitialized()) {
4188 CHECK(!super_class->IsInterface());
4189 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004190 StackHandleScope<1> hs(self);
4191 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004192 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004193 if (!super_initialized) {
4194 // The super class was verified ahead of entering initializing, we should only be here if
4195 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004196 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004197 << "Super class initialization failed for "
4198 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004199 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004200 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004201 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004202 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004203 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004204 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004205 return false;
4206 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004207 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004208 }
4209
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004210 const size_t num_static_fields = klass->NumStaticFields();
4211 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004212 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004213 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004214 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004215 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004216 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004217 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004218
4219 // Eagerly fill in static fields so that the we don't have to do as many expensive
4220 // Class::FindStaticField in ResolveField.
4221 for (size_t i = 0; i < num_static_fields; ++i) {
4222 mirror::ArtField* field = klass->GetStaticField(i);
4223 const uint32_t field_idx = field->GetDexFieldIndex();
4224 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4225 if (resolved_field == nullptr) {
4226 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004227 } else {
4228 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004229 }
4230 }
4231
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004232 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4233 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004234 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004235 ClassDataItemIterator field_it(dex_file, class_data);
4236 if (value_it.HasNext()) {
4237 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004238 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004239 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004240 StackHandleScope<1> hs2(self);
4241 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004242 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004243 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004244 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004245 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004246 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004247 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004248 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004249 }
4250 }
4251 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004252
Ian Rogersd91d6d62013-09-25 20:26:14 -07004253 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004254 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004255 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004256 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004257 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004258 }
4259
Ian Rogers7b078e82014-09-10 14:44:24 -07004260 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004261 uint64_t t1 = NanoTime();
4262
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004263 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004264 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004265 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004266
4267 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004268 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004269 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004270 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004271 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004272 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4273 RuntimeStats* thread_stats = self->GetStats();
4274 ++global_stats->class_init_count;
4275 ++thread_stats->class_init_count;
4276 global_stats->class_init_time_ns += (t1 - t0);
4277 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004278 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004279 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004280 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004281 std::string temp;
4282 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004283 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004284 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004285 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004286 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004287 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004288 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004289 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004290}
4291
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004292bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004293 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004294 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004295 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004296 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004297 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004298 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004299
4300 // When we wake up, repeat the test for init-in-progress. If
4301 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004302 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004303 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004304 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004305 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004306 return false;
4307 }
4308 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004309 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004310 continue;
4311 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004312 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004313 // Compile time initialization failed.
4314 return false;
4315 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004316 if (klass->IsErroneous()) {
4317 // The caller wants an exception, but it was thrown in a
4318 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004319 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004320 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004321 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004322 return false;
4323 }
4324 if (klass->IsInitialized()) {
4325 return true;
4326 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004327 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004328 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004329 }
Ian Rogers07140832014-09-30 15:43:59 -07004330 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004331}
4332
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004333bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004334 if (klass->IsInterface()) {
4335 return true;
4336 }
Ian Rogers151f2212014-05-06 11:27:27 -07004337 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004338 Thread* self = Thread::Current();
4339 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004340 MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4341 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004342 if (klass->HasSuperClass() &&
4343 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004344 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4345 mh.ChangeMethod(klass->GetVTableEntry(i));
4346 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004347 if (mh.GetMethod() != super_mh.GetMethod() &&
Ian Rogersded66a02014-10-28 18:12:55 -07004348 !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004349 ThrowLinkageError(klass.Get(),
4350 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004351 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004352 PrettyMethod(mh.GetMethod()).c_str(),
4353 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004354 return false;
4355 }
4356 }
4357 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004358 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004359 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4360 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4361 for (uint32_t j = 0; j < num_methods; ++j) {
4362 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4363 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004364 if (mh.GetMethod() != super_mh.GetMethod() &&
Ian Rogersded66a02014-10-28 18:12:55 -07004365 !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004366 ThrowLinkageError(klass.Get(),
4367 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004368 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004369 PrettyMethod(mh.GetMethod()).c_str(),
4370 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004371 return false;
4372 }
4373 }
4374 }
4375 }
4376 return true;
4377}
4378
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004379bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4380 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004381 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004382 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004383 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004384 return true;
4385 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004386 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004387 if (!success) {
4388 if (can_init_fields && can_init_parents) {
4389 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4390 }
4391 } else {
4392 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004393 }
4394 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004395}
4396
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004397void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4398 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4399 if (fields != nullptr) {
4400 for (int index = 0; index < fields->GetLength(); index ++) {
4401 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4402 fields->Get(index)->SetDeclaringClass(new_class);
4403 }
4404 }
4405 }
4406
4407 fields = new_class->GetSFields();
4408 if (fields != nullptr) {
4409 for (int index = 0; index < fields->GetLength(); index ++) {
4410 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4411 fields->Get(index)->SetDeclaringClass(new_class);
4412 }
4413 }
4414 }
4415
4416 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4417 if (methods != nullptr) {
4418 for (int index = 0; index < methods->GetLength(); index ++) {
4419 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4420 methods->Get(index)->SetDeclaringClass(new_class);
4421 }
4422 }
4423 }
4424
4425 methods = new_class->GetVirtualMethods();
4426 if (methods != nullptr) {
4427 for (int index = 0; index < methods->GetLength(); index ++) {
4428 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4429 methods->Get(index)->SetDeclaringClass(new_class);
4430 }
4431 }
4432 }
4433}
4434
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004435bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4436 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004437 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004438 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004439
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004440 if (!LinkSuperClass(klass)) {
4441 return false;
4442 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004443 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4444 self, Runtime::Current()->GetImtUnimplementedMethod());
4445 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004446 return false;
4447 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004448 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004449 return false;
4450 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004451 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004452 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004453 return false;
4454 }
4455 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004456 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004457
4458 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4459 // We don't need to retire this class as it has no embedded tables or it was created the
4460 // correct size during class linker initialization.
4461 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4462
4463 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004464 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004465 }
4466
4467 // This will notify waiters on klass that saw the not yet resolved
4468 // class in the class_table_ during EnsureResolved.
4469 klass->SetStatus(mirror::Class::kStatusResolved, self);
4470 *new_class = klass.Get();
4471 } else {
4472 CHECK(!klass->IsResolved());
4473 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004474 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004475 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004476 CHECK(self->IsExceptionPending()); // Expect an OOME.
4477 klass->SetStatus(mirror::Class::kStatusError, self);
4478 return false;
4479 }
4480
4481 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4482 StackHandleScope<1> hs(self);
4483 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4484 ObjectLock<mirror::Class> lock(self, new_class_h);
4485
4486 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4487
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004488 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4489 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004490 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004491
4492 // This will notify waiters on temp class that saw the not yet resolved class in the
4493 // class_table_ during EnsureResolved.
4494 klass->SetStatus(mirror::Class::kStatusRetired, self);
4495
4496 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4497 // This will notify waiters on new_class that saw the not yet resolved
4498 // class in the class_table_ during EnsureResolved.
4499 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004500 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004501 return true;
4502}
4503
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004504bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004505 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004506 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4507 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004508 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004509 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004510 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004511 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004512 return false;
4513 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004514 // Verify
4515 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004516 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004517 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004518 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004519 return false;
4520 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004521 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004522 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004523 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004524 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004525 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004526 for (size_t i = 0; i < interfaces->Size(); i++) {
4527 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004528 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004529 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004530 DCHECK(Thread::Current()->IsExceptionPending());
4531 return false;
4532 }
4533 // Verify
4534 if (!klass->CanAccess(interface)) {
4535 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004536 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004537 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004538 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004539 return false;
4540 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004541 }
4542 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004543 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004544 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004545 return true;
4546}
4547
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004548bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004549 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004550 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004551 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004552 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004553 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004554 return false;
4555 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004556 return true;
4557 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004558 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004559 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4560 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004561 return false;
4562 }
4563 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004564 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004565 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004566 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004567 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004568 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004569 return false;
4570 }
4571 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004572 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004573 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004574 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004575 return false;
4576 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004577
Brian Carlstromf3632832014-05-20 15:36:53 -07004578 // Inherit kAccClassIsFinalizable from the superclass in case this
4579 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004580 if (super->IsFinalizable()) {
4581 klass->SetFinalizable();
4582 }
4583
Elliott Hughes2da50362011-10-10 16:57:08 -07004584 // Inherit reference flags (if any) from the superclass.
4585 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4586 if (reference_flags != 0) {
4587 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4588 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004589 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004590 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004591 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004592 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004593 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004594 return false;
4595 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004596
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004597 if (kIsDebugBuild) {
4598 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004599 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004600 CHECK(super->IsResolved());
4601 super = super->GetSuperClass();
4602 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004603 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004604 return true;
4605}
4606
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004607// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004608bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004609 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4610 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004611 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004612 if (klass->IsInterface()) {
4613 // No vtable.
4614 size_t count = klass->NumVirtualMethods();
4615 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004616 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004617 return false;
4618 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004619 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004620 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004621 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004622 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4623 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004624 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004625 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004626}
4627
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004628// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4629// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4630// caches in the implementation below.
4631class MethodNameAndSignatureComparator FINAL : public ValueObject {
4632 public:
4633 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4634 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4635 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4636 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004637 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4638 }
4639
4640 const char* GetName() {
4641 if (name_ == nullptr) {
4642 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4643 }
4644 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004645 }
4646
4647 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4648 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4649 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4650 const DexFile* other_dex_file = other->GetDexFile();
4651 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4652 if (dex_file_ == other_dex_file) {
4653 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4654 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004655 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004656 uint32_t other_name_len;
4657 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4658 &other_name_len);
4659 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4660 return false;
4661 }
4662 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4663 }
4664
4665 private:
4666 // Dex file for the method to compare against.
4667 const DexFile* const dex_file_;
4668 // MethodId for the method to compare against.
4669 const DexFile::MethodId* const mid_;
4670 // Lazily computed name from the dex file's strings.
4671 const char* name_;
4672 // Lazily computed name length.
4673 uint32_t name_len_;
4674};
4675
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004676class LinkVirtualHashTable {
4677 public:
4678 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4679 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4680 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4681 }
4682 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4683 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4684 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004685 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004686 uint32_t index = hash % hash_size_;
4687 // Linear probe until we have an empty slot.
4688 while (hash_table_[index] != invalid_index_) {
4689 if (++index == hash_size_) {
4690 index = 0;
4691 }
4692 }
4693 hash_table_[index] = virtual_method_index;
4694 }
4695 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4696 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4697 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004698 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004699 size_t index = hash % hash_size_;
4700 while (true) {
4701 const uint32_t value = hash_table_[index];
4702 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4703 // the block and can safely assume not found.
4704 if (value == invalid_index_) {
4705 break;
4706 }
4707 if (value != removed_index_) { // This signifies not already overriden.
4708 mirror::ArtMethod* virtual_method =
4709 klass_->GetVirtualMethodDuringLinking(value);
4710 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4711 hash_table_[index] = removed_index_;
4712 return value;
4713 }
4714 }
4715 if (++index == hash_size_) {
4716 index = 0;
4717 }
4718 }
4719 return GetNotFoundIndex();
4720 }
4721 static uint32_t GetNotFoundIndex() {
4722 return invalid_index_;
4723 }
4724
4725 private:
4726 static const uint32_t invalid_index_;
4727 static const uint32_t removed_index_;
4728
4729 Handle<mirror::Class> klass_;
4730 const size_t hash_size_;
4731 uint32_t* const hash_table_;
4732};
4733
4734const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4735const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4736
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004737bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004738 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004739 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004740 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4741 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004742 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004743 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004744 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004745 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4746 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4747 if (UNLIKELY(vtable.Get() == nullptr)) {
4748 CHECK(self->IsExceptionPending()); // OOME.
4749 return false;
4750 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004751 for (size_t i = 0; i < super_vtable_length; i++) {
4752 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004753 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004754 if (num_virtual_methods == 0) {
4755 klass->SetVTable(vtable.Get());
4756 return true;
4757 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004758 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004759 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4760 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4761 if (num_virtual_methods == 0) {
4762 klass->SetVTable(super_vtable);
4763 return true;
4764 }
4765 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004766 if (UNLIKELY(vtable.Get() == nullptr)) {
4767 CHECK(self->IsExceptionPending()); // OOME.
4768 return false;
4769 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004770 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004771 // How the algorithm works:
4772 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4773 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4774 // method which has not been matched to a vtable method, and j if the virtual method at the
4775 // index overrode the super virtual method at index j.
4776 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4777 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4778 // the need for the initial vtable which we later shrink back down).
4779 // 3. Add non overridden methods to the end of the vtable.
4780 static constexpr size_t kMaxStackHash = 250;
4781 const size_t hash_table_size = num_virtual_methods * 3;
4782 uint32_t* hash_table_ptr;
4783 std::unique_ptr<uint32_t[]> hash_heap_storage;
4784 if (hash_table_size <= kMaxStackHash) {
4785 hash_table_ptr = reinterpret_cast<uint32_t*>(
4786 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4787 } else {
4788 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4789 hash_table_ptr = hash_heap_storage.get();
4790 }
4791 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4792 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004793 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004794 hash_table.Add(i);
4795 }
4796 // Loop through each super vtable method and see if they are overriden by a method we added to
4797 // the hash table.
4798 for (size_t j = 0; j < super_vtable_length; ++j) {
4799 // Search the hash table to see if we are overidden by any method.
4800 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4801 MethodNameAndSignatureComparator super_method_name_comparator(
4802 super_method->GetInterfaceMethodIfProxy());
4803 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4804 if (hash_index != hash_table.GetNotFoundIndex()) {
4805 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4806 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4807 super_method->GetAccessFlags())) {
4808 if (super_method->IsFinal()) {
4809 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4810 PrettyMethod(virtual_method).c_str(),
4811 super_method->GetDeclaringClassDescriptor());
4812 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004813 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004814 vtable->SetWithoutChecks<false>(j, virtual_method);
4815 virtual_method->SetMethodIndex(j);
4816 } else {
4817 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004818 << " would have incorrectly overridden the package-private method in "
4819 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004820 }
4821 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004822 }
4823 // Add the non overridden methods at the end.
4824 size_t actual_count = super_vtable_length;
4825 for (size_t i = 0; i < num_virtual_methods; ++i) {
4826 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4827 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4828 if (method_idx < super_vtable_length &&
4829 local_method == vtable->GetWithoutChecks(method_idx)) {
4830 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004831 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004832 vtable->SetWithoutChecks<false>(actual_count, local_method);
4833 local_method->SetMethodIndex(actual_count);
4834 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004835 }
4836 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004837 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004838 return false;
4839 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004840 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004841 CHECK_LE(actual_count, max_count);
4842 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004843 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004844 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004845 CHECK(self->IsExceptionPending()); // OOME.
4846 return false;
4847 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004848 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004849 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004850 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004851 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004852 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004853 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4854 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004855 return false;
4856 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004857 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4858 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004859 CHECK(self->IsExceptionPending()); // OOME.
4860 return false;
4861 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004862 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004863 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004864 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004865 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004866 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004867 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004868 }
4869 return true;
4870}
4871
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004872bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4873 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4874 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004875 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004876 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004877 const bool has_superclass = klass->HasSuperClass();
4878 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4879 const bool have_interfaces = interfaces.Get() != nullptr;
4880 const size_t num_interfaces =
4881 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4882 if (num_interfaces == 0) {
4883 if (super_ifcount == 0) {
4884 // Class implements no interfaces.
4885 DCHECK_EQ(klass->GetIfTableCount(), 0);
4886 DCHECK(klass->GetIfTable() == nullptr);
4887 return true;
4888 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004889 // Class implements same interfaces as parent, are any of these not marker interfaces?
4890 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004891 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004892 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004893 if (super_iftable->GetMethodArrayCount(i) > 0) {
4894 has_non_marker_interface = true;
4895 break;
4896 }
4897 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004898 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004899 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004900 klass->SetIfTable(super_iftable);
4901 return true;
4902 }
4903 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004904 size_t ifcount = super_ifcount + num_interfaces;
4905 for (size_t i = 0; i < num_interfaces; i++) {
4906 mirror::Class* interface = have_interfaces ?
4907 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4908 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004909 if (UNLIKELY(!interface->IsInterface())) {
4910 std::string temp;
4911 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4912 PrettyDescriptor(klass.Get()).c_str(),
4913 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4914 return false;
4915 }
4916 ifcount += interface->GetIfTableCount();
4917 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004918 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004919 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004920 CHECK(self->IsExceptionPending()); // OOME.
4921 return false;
4922 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004923 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004924 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004925 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004926 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004927 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004928 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004929 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004930 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004931 // Flatten the interface inheritance hierarchy.
4932 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004933 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004934 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4935 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004936 // Check if interface is already in iftable
4937 bool duplicate = false;
4938 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004939 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004940 if (existing_interface == interface) {
4941 duplicate = true;
4942 break;
4943 }
4944 }
4945 if (!duplicate) {
4946 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004947 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004948 // Add this interface's non-duplicate super-interfaces.
4949 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004950 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004951 bool super_duplicate = false;
4952 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004953 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004954 if (existing_interface == super_interface) {
4955 super_duplicate = true;
4956 break;
4957 }
4958 }
4959 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004960 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004961 }
4962 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004963 }
4964 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004965 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004966 // Shrink iftable in case duplicates were found
4967 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004968 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004969 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004970 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004971 CHECK(self->IsExceptionPending()); // OOME.
4972 return false;
4973 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004974 ifcount = idx;
4975 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004976 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004977 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004978 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004979 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004980 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004981 return true;
4982 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004983 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004984 size_t max_miranda_methods = 0; // The max size of miranda_list.
4985 for (size_t i = 0; i < ifcount; ++i) {
4986 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4987 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004988 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004989 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004990 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4991 hs.NewHandle(klass->GetVTableDuringLinking()));
4992 // Copy the IMT from the super class if possible.
4993 bool extend_super_iftable = false;
4994 if (has_superclass) {
4995 mirror::Class* super_class = klass->GetSuperClass();
4996 extend_super_iftable = true;
4997 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4998 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4999 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5000 }
5001 } else {
5002 // No imt in the super class, need to reconstruct from the iftable.
5003 mirror::IfTable* if_table = super_class->GetIfTable();
5004 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5005 const size_t length = super_class->GetIfTableCount();
5006 for (size_t i = 0; i < length; ++i) {
5007 mirror::Class* interface = iftable->GetInterface(i);
5008 const size_t num_virtuals = interface->NumVirtualMethods();
5009 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5010 DCHECK_EQ(num_virtuals, method_array_count);
5011 if (method_array_count == 0) {
5012 continue;
5013 }
5014 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5015 for (size_t j = 0; j < num_virtuals; ++j) {
5016 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5017 if (method->IsMiranda()) {
5018 continue;
5019 }
5020 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5021 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5022 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5023 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5024 out_imt->SetReference(imt_index, method);
5025 } else if (imt_ref != conflict_method) {
5026 out_imt->SetReference(imt_index, conflict_method);
5027 }
5028 }
5029 }
5030 }
5031 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005032 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005033 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005034 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005035 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005036 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005037 const bool is_super = i < super_ifcount;
5038 const bool super_interface = is_super && extend_super_iftable;
5039 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5040 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5041 if (super_interface) {
5042 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5043 DCHECK(if_table != nullptr);
5044 DCHECK(if_table->GetMethodArray(i) != nullptr);
5045 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005046 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005047 AsObjectArray<mirror::ArtMethod>());
5048 // We are overwriting a super class interface, try to only virtual methods instead of the
5049 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005050 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005051 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005052 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005053 // A new interface, we need the whole vtable incase a new interface method is implemented
5054 // in the whole superclass.
5055 input_array = vtable;
5056 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005057 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005058 CHECK(self->IsExceptionPending()); // OOME.
5059 return false;
5060 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005061 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005062 if (input_array.Get() == nullptr) {
5063 // If the added virtual methods is empty, do nothing.
5064 DCHECK(super_interface);
5065 continue;
5066 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005067 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005068 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005069 MethodNameAndSignatureComparator interface_name_comparator(
5070 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005071 int32_t k;
5072 // For each method listed in the interface's method list, find the
5073 // matching method in our class's method list. We want to favor the
5074 // subclass over the superclass, which just requires walking
5075 // back from the end of the vtable. (This only matters if the
5076 // superclass defines a private method and this class redefines
5077 // it -- otherwise it would use the same vtable slot. In .dex files
5078 // those don't end up in the virtual method table, so it shouldn't
5079 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005080 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5081 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005082 mirror::ArtMethod* vtable_method_for_name_comparison =
5083 vtable_method->GetInterfaceMethodIfProxy();
5084 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005085 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005086 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005087 ThrowIllegalAccessError(
5088 klass.Get(),
5089 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005090 PrettyMethod(vtable_method).c_str(),
5091 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005092 return false;
5093 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005094 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005095 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005096 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5097 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5098 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5099 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5100 out_imt->SetReference(imt_index, vtable_method);
5101 } else if (imt_ref != conflict_method) {
5102 // If we are not a conflict and we have the same signature and name as the imt entry,
5103 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005104 MethodNameAndSignatureComparator imt_ref_name_comparator(
5105 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005106 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005107 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005108 out_imt->SetReference(imt_index, vtable_method);
5109 } else {
5110 out_imt->SetReference(imt_index, conflict_method);
5111 }
Jeff Hao88474b42013-10-23 16:24:40 -07005112 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005113 break;
5114 }
5115 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005116 if (k < 0 && !super_interface) {
5117 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005118 for (size_t l = 0; l < miranda_list_size; ++l) {
5119 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005120 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005121 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005122 break;
5123 }
5124 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005125 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005126 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005127 miranda_method = interface_method->Clone(self)->AsArtMethod();
5128 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005129 CHECK(self->IsExceptionPending()); // OOME.
5130 return false;
5131 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005132 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005133 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005134 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005135 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005136 }
5137 }
5138 }
5139 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005140 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005141 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005142 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005143 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5144 if (old_method_count == 0) {
5145 virtuals = AllocArtMethodArray(self, new_method_count);
5146 } else {
5147 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5148 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005149 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005150 CHECK(self->IsExceptionPending()); // OOME.
5151 return false;
5152 }
5153 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005154
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005155 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005156 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005157 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005158 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005159 CHECK(self->IsExceptionPending()); // OOME.
5160 return false;
5161 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005162 for (size_t i = 0; i < miranda_list_size; ++i) {
5163 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005164 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005165 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5166 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5167 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005168 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005169 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005170 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005171 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005172 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005173
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005174 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005175 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5176 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5177 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005178 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005179 }
5180
Ian Rogers7b078e82014-09-10 14:44:24 -07005181 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005182 return true;
5183}
5184
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005185bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005186 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005187 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005188}
5189
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005190bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005191 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005192 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005193}
5194
Brian Carlstromdbc05252011-09-09 01:59:59 -07005195struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005196 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5197 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005198 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005199 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005200 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005201 // 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 -07005202 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5203 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005204 if (type1 != type2) {
5205 bool is_primitive1 = type1 != Primitive::kPrimNot;
5206 bool is_primitive2 = type2 != Primitive::kPrimNot;
Fred Shih37f05ef2014-07-16 18:38:08 -07005207 if (type1 != type2) {
5208 if (is_primitive1 && is_primitive2) {
5209 // Larger primitive types go first.
5210 return Primitive::ComponentSize(type1) > Primitive::ComponentSize(type2);
5211 } else {
5212 // Reference always goes first.
5213 return !is_primitive1;
5214 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08005215 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005216 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005217 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005218 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005219 }
5220};
5221
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005222bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005223 size_t* class_size) {
5224 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005225 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005226 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005227
Brian Carlstromea46f952013-07-30 01:26:50 -07005228 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005229 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005230
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005231 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005232 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005233 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005234 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
5235 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
5236 // Static fields come after the embedded tables.
5237 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
Fred Shih37f05ef2014-07-16 18:38:08 -07005238 0, 0, 0, 0, 0);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005239 }
5240 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005241 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005242 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005243 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005244 CHECK(super_class->IsResolved())
5245 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005246 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005247 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005248 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005249
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005250 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005251
Brian Carlstromdbc05252011-09-09 01:59:59 -07005252 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005253 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005254 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005255 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005256 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005257 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005258 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005259 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005260 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005261 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005262 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5263 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005264
Fred Shih381e4ca2014-08-25 17:24:27 -07005265 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005266 size_t current_field = 0;
5267 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005268 FieldGaps gaps;
5269
Brian Carlstromdbc05252011-09-09 01:59:59 -07005270 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005271 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005272 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005273 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005274 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005275 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005276 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005277 if (UNLIKELY(!IsAligned<4>(field_offset.Uint32Value()))) {
5278 MemberOffset old_offset = field_offset;
5279 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5280 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5281 }
5282 DCHECK(IsAligned<4>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005283 grouped_and_sorted_fields.pop_front();
5284 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005285 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005286 field->SetOffset(field_offset);
5287 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005288 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005289 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5290 // otherwise we could end up with suboptimal gap fills.
5291 ShuffleForward<8>(num_fields, &current_field, &field_offset,
5292 fields, &grouped_and_sorted_fields, &gaps);
5293 ShuffleForward<4>(num_fields, &current_field, &field_offset,
5294 fields, &grouped_and_sorted_fields, &gaps);
5295 ShuffleForward<2>(num_fields, &current_field, &field_offset,
5296 fields, &grouped_and_sorted_fields, &gaps);
5297 ShuffleForward<1>(num_fields, &current_field, &field_offset,
5298 fields, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005299 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5300 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005301 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005302
Elliott Hughesadb460d2011-10-05 17:02:34 -07005303 // 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 -07005304 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005305 // We know there are no non-reference fields in the Reference classes, and we know
5306 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005307 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005308 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005309 --num_reference_fields;
5310 }
5311
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005312 if (kIsDebugBuild) {
5313 // Make sure that all reference fields appear before
5314 // non-reference fields, and all double-wide fields are aligned.
5315 bool seen_non_ref = false;
5316 for (size_t i = 0; i < num_fields; i++) {
5317 mirror::ArtField* field = fields->Get(i);
Ian Rogerscf7f1912014-10-22 22:06:39 -07005318 if ((false)) { // enable to debug field layout
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005319 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005320 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005321 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07005322 << " offset="
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005323 << field->GetField32(mirror::ArtField::OffsetOffset());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005324 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005325 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005326 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005327 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005328 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005329 is_primitive = true; // We lied above, so we have to expect a lie here.
5330 }
5331 if (is_primitive) {
5332 if (!seen_non_ref) {
5333 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07005334 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005335 }
5336 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07005337 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005338 }
5339 }
5340 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005341 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005342 }
5343 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005344
5345 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005346 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005347 if (is_static) {
5348 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005349 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005350 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005351 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005352 if (!klass->IsVariableSize()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005353 std::string temp;
5354 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005355 size_t previous_size = klass->GetObjectSize();
5356 if (previous_size != 0) {
5357 // Make sure that we didn't originally have an incorrect size.
Ian Rogers1ff3c982014-08-12 02:30:58 -07005358 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005359 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005360 klass->SetObjectSize(size);
5361 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005362 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005363 return true;
5364}
5365
5366// Set the bitmap of reference offsets, refOffsets, from the ifields
5367// list.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005368void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005369 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005370 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005371 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005372 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005373 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005374 // Compute reference offsets unless our superclass overflowed.
5375 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5376 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
5377 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
5378 // All of the fields that contain object references are guaranteed
5379 // to be at the beginning of the fields list.
5380 for (size_t i = 0; i < num_reference_fields; ++i) {
5381 // Note that byte_offset is the offset from the beginning of
5382 // object, not the offset into instance data
5383 mirror::ArtField* field = fields->Get(i);
5384 MemberOffset byte_offset = field->GetOffsetDuringLinking();
5385 uint32_t displaced_bitmap_position =
5386 (byte_offset.Uint32Value() - mirror::kObjectHeaderSize) /
5387 sizeof(mirror::HeapReference<mirror::Object>);
5388 if (displaced_bitmap_position >= 32) {
5389 // Can't encode offset so fall back on slow-path.
5390 reference_offsets = mirror::Class::kClassWalkSuper;
5391 break;
5392 } else {
5393 reference_offsets |= (1 << displaced_bitmap_position);
5394 }
5395 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005396 }
5397 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005398 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005399}
5400
Mathieu Chartier590fee92013-09-13 13:46:47 -07005401mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005402 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005403 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005404 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005405 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005406 return resolved;
5407 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005408 uint32_t utf16_length;
5409 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005410 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005411 dex_cache->SetResolvedString(string_idx, string);
5412 return string;
5413}
5414
Mathieu Chartier590fee92013-09-13 13:46:47 -07005415mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005416 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005417 StackHandleScope<2> hs(Thread::Current());
5418 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5419 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005420 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5421}
5422
5423mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005424 Handle<mirror::DexCache> dex_cache,
5425 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005426 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005427 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005428 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005429 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005430 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005431 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005432 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005433 // TODO: we used to throw here if resolved's class loader was not the
5434 // boot class loader. This was to permit different classes with the
5435 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005436 dex_cache->SetResolvedType(type_idx, resolved);
5437 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005438 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005439 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005440 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005441 StackHandleScope<1> hs(self);
5442 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005443 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005444 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005445 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005446 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005447 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005448 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005449 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005450 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005451 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005452 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005453 return resolved;
5454}
5455
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005456mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005457 Handle<mirror::DexCache> dex_cache,
5458 Handle<mirror::ClassLoader> class_loader,
5459 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005460 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005461 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005462 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005463 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005464 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005465 return resolved;
5466 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005467 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005468 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005469 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005470 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005471 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005472 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005473 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005474 // Scan using method_idx, this saves string compares but will only hit for matching dex
5475 // caches/files.
5476 switch (type) {
5477 case kDirect: // Fall-through.
5478 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005479 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005480 break;
5481 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005482 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005483 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005484 break;
5485 case kSuper: // Fall-through.
5486 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005487 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005488 break;
5489 default:
5490 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005491 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005492 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005493 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005494 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005495 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005496 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005497 switch (type) {
5498 case kDirect: // Fall-through.
5499 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005500 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005501 break;
5502 case kInterface:
5503 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005504 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005505 break;
5506 case kSuper: // Fall-through.
5507 case kVirtual:
5508 resolved = klass->FindVirtualMethod(name, signature);
5509 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005510 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005511 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005512 // If we found a method, check for incompatible class changes.
5513 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005514 // Be a good citizen and update the dex cache to speed subsequent calls.
5515 dex_cache->SetResolvedMethod(method_idx, resolved);
5516 return resolved;
5517 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005518 // If we had a method, it's an incompatible-class-change error.
5519 if (resolved != nullptr) {
5520 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5521 } else {
5522 // We failed to find the method which means either an access error, an incompatible class
5523 // change, or no such method. First try to find the method among direct and virtual methods.
5524 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5525 const Signature signature = dex_file.GetMethodSignature(method_id);
5526 switch (type) {
5527 case kDirect:
5528 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005529 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005530 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5531 // have had a resolved method before, which triggers the "true" branch above.
5532 break;
5533 case kInterface:
5534 case kVirtual:
5535 case kSuper:
5536 resolved = klass->FindDirectMethod(name, signature);
5537 break;
5538 }
5539
5540 // If we found something, check that it can be accessed by the referrer.
5541 if (resolved != nullptr && referrer.Get() != nullptr) {
5542 mirror::Class* methods_class = resolved->GetDeclaringClass();
5543 mirror::Class* referring_class = referrer->GetDeclaringClass();
5544 if (!referring_class->CanAccess(methods_class)) {
5545 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5546 resolved, type);
5547 return nullptr;
5548 } else if (!referring_class->CanAccessMember(methods_class,
5549 resolved->GetAccessFlags())) {
5550 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5551 return nullptr;
5552 }
5553 }
5554
5555 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5556 // methods and throw if we find the method there. If we find nothing, throw a
5557 // NoSuchMethodError.
5558 switch (type) {
5559 case kDirect:
5560 case kStatic:
5561 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005562 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005563 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005564 resolved = klass->FindInterfaceMethod(name, signature);
5565 if (resolved != nullptr) {
5566 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5567 } else {
5568 ThrowNoSuchMethodError(type, klass, name, signature);
5569 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005570 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005571 break;
5572 case kInterface:
5573 if (resolved != nullptr) {
5574 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005575 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005576 resolved = klass->FindVirtualMethod(name, signature);
5577 if (resolved != nullptr) {
5578 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5579 } else {
5580 ThrowNoSuchMethodError(type, klass, name, signature);
5581 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005582 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005583 break;
5584 case kSuper:
Andreas Gampedf733752014-08-25 20:55:01 -07005585 if (resolved != nullptr) {
5586 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5587 } else {
5588 ThrowNoSuchMethodError(type, klass, name, signature);
5589 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005590 break;
5591 case kVirtual:
5592 if (resolved != nullptr) {
5593 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5594 } else {
5595 resolved = klass->FindInterfaceMethod(name, signature);
5596 if (resolved != nullptr) {
5597 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5598 } else {
5599 ThrowNoSuchMethodError(type, klass, name, signature);
5600 }
5601 }
5602 break;
5603 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005604 }
5605 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005606 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005607 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005608}
5609
Mathieu Chartier590fee92013-09-13 13:46:47 -07005610mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005611 Handle<mirror::DexCache> dex_cache,
5612 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005613 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005614 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005615 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005616 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005617 return resolved;
5618 }
5619 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005620 Thread* const self = Thread::Current();
5621 StackHandleScope<1> hs(self);
5622 Handle<mirror::Class> klass(
5623 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005624 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005625 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005626 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005627 }
5628
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005629 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005630 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005631 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005632 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005633 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005634
Andreas Gampe58a5af82014-07-31 16:23:49 -07005635 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005636 const char* name = dex_file.GetFieldName(field_id);
5637 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5638 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005639 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005640 } else {
5641 resolved = klass->FindInstanceField(name, type);
5642 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005643 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005644 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005645 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005646 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005647 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005648 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005649 return resolved;
5650}
5651
Brian Carlstromea46f952013-07-30 01:26:50 -07005652mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005653 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005654 Handle<mirror::DexCache> dex_cache,
5655 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005656 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005657 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005658 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005659 return resolved;
5660 }
5661 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005662 Thread* self = Thread::Current();
5663 StackHandleScope<1> hs(self);
5664 Handle<mirror::Class> klass(
5665 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005666 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005667 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005668 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005669 }
5670
Ian Rogersdfb325e2013-10-30 01:00:44 -07005671 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5672 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005673 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005674 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005675 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005676 dex_cache->SetResolvedField(field_idx, resolved);
5677 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005678 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005679 }
5680 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005681}
5682
Brian Carlstromea46f952013-07-30 01:26:50 -07005683const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005684 uint32_t* length) {
5685 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5686 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005687 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005688 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005689 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005690}
5691
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005692void ClassLinker::DumpAllClasses(int flags) {
5693 if (dex_cache_image_class_lookup_required_) {
5694 MoveImageClassesToClassTable();
5695 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005696 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5697 // 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 -08005698 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005699 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005700 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005701 for (GcRoot<mirror::Class>& it : class_table_) {
5702 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005703 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005704 }
5705
5706 for (size_t i = 0; i < all_classes.size(); ++i) {
5707 all_classes[i]->DumpClass(std::cerr, flags);
5708 }
5709}
5710
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005711static OatFile::OatMethod CreateOatMethod(const void* code, const uint8_t* gc_map,
5712 bool is_portable) {
5713 CHECK_EQ(kUsePortableCompiler, is_portable);
5714 CHECK(code != nullptr);
5715 const uint8_t* base;
5716 uint32_t code_offset, gc_map_offset;
5717 if (gc_map == nullptr) {
5718 base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5719 base -= sizeof(void*); // Move backward so that code_offset != 0.
5720 code_offset = sizeof(void*);
5721 gc_map_offset = 0;
5722 } else {
5723 // TODO: 64bit support.
5724 base = nullptr; // Base of data in oat file, ie 0.
5725 code_offset = PointerToLowMemUInt32(code);
5726 gc_map_offset = PointerToLowMemUInt32(gc_map);
5727 }
5728 return OatFile::OatMethod(base, code_offset, gc_map_offset);
5729}
5730
5731bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5732 return (entry_point == GetPortableResolutionStub()) ||
5733 (portable_resolution_trampoline_ == entry_point);
5734}
5735
5736bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5737 return (entry_point == GetQuickResolutionStub()) ||
5738 (quick_resolution_trampoline_ == entry_point);
5739}
5740
5741bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5742 return (entry_point == GetPortableToInterpreterBridge());
5743 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5744}
5745
5746bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5747 return (entry_point == GetQuickToInterpreterBridge()) ||
5748 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5749}
5750
5751bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5752 return (entry_point == GetQuickGenericJniStub()) ||
5753 (quick_generic_jni_trampoline_ == entry_point);
5754}
5755
5756const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5757 return GetQuickGenericJniStub();
5758}
5759
5760void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5761 bool is_portable) const {
5762 OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr, is_portable);
5763 oat_method.LinkMethod(method);
5764 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5765 // Create bridges to transition between different kinds of compiled bridge.
5766 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5767 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5768 } else {
5769 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5770 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5771 method->SetIsPortableCompiled();
5772 }
5773}
5774
5775void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5776 if (!method->IsNative()) {
5777 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5778 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5779 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5780 } else {
5781 const void* quick_method_code = GetQuickGenericJniStub();
5782 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, nullptr, false);
5783 oat_method.LinkMethod(method);
5784 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5785 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5786 }
5787}
5788
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005789void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005790 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005791 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005792 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005793 MoveImageClassesToClassTable();
5794 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005795 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005796 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5797 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005798}
5799
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005800size_t ClassLinker::NumLoadedClasses() {
5801 if (dex_cache_image_class_lookup_required_) {
5802 MoveImageClassesToClassTable();
5803 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005804 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005805 // Only return non zygote classes since these are the ones which apps which care about.
5806 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005807}
5808
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005809pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005810 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005811}
5812
5813pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005814 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005815}
5816
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005817void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005818 DCHECK(!init_done_);
5819
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005820 DCHECK(klass != nullptr);
5821 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005822
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005823 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005824 DCHECK(class_roots != nullptr);
5825 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005826 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005827}
5828
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005829const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5830 static const char* class_roots_descriptors[] = {
5831 "Ljava/lang/Class;",
5832 "Ljava/lang/Object;",
5833 "[Ljava/lang/Class;",
5834 "[Ljava/lang/Object;",
5835 "Ljava/lang/String;",
5836 "Ljava/lang/DexCache;",
5837 "Ljava/lang/ref/Reference;",
5838 "Ljava/lang/reflect/ArtField;",
5839 "Ljava/lang/reflect/ArtMethod;",
5840 "Ljava/lang/reflect/Proxy;",
5841 "[Ljava/lang/String;",
5842 "[Ljava/lang/reflect/ArtField;",
5843 "[Ljava/lang/reflect/ArtMethod;",
5844 "Ljava/lang/ClassLoader;",
5845 "Ljava/lang/Throwable;",
5846 "Ljava/lang/ClassNotFoundException;",
5847 "Ljava/lang/StackTraceElement;",
5848 "Z",
5849 "B",
5850 "C",
5851 "D",
5852 "F",
5853 "I",
5854 "J",
5855 "S",
5856 "V",
5857 "[Z",
5858 "[B",
5859 "[C",
5860 "[D",
5861 "[F",
5862 "[I",
5863 "[J",
5864 "[S",
5865 "[Ljava/lang/StackTraceElement;",
5866 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005867 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5868 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005869
5870 const char* descriptor = class_roots_descriptors[class_root];
5871 CHECK(descriptor != nullptr);
5872 return descriptor;
5873}
5874
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005875std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5876 const {
5877 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005878 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005879}
5880
5881bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5882 const GcRoot<mirror::Class>& b) {
5883 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5884 return false;
5885 }
5886 std::string temp;
5887 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5888}
5889
5890std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5891 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005892 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005893}
5894
5895bool ClassLinker::ClassDescriptorHashEquals::operator()(
5896 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5897 if (a.Read()->GetClassLoader() != b.second) {
5898 return false;
5899 }
5900 return a.Read()->DescriptorEquals(b.first);
5901}
5902
5903bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5904 const char* descriptor) {
5905 return a.Read()->DescriptorEquals(descriptor);
5906}
5907
5908std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005909 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005910}
5911
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005912} // namespace art