blob: aaf2da7fcda29244b8e9a58fab9f4cc34e84ddd9 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070020#include <iostream>
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070022#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070024#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070025#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070026
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080028#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010029#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080030#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080031#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000033#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080034#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070035#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070036#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070037#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
40#include "gc/heap.h"
41#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070042#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070043#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070044#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070045#include "leb128.h"
Ian Rogers1ff3c982014-08-12 02:30:58 -070046#include "method_helper-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080047#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070048#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070049#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070050#include "mirror/art_field-inl.h"
51#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080052#include "mirror/class.h"
53#include "mirror/class-inl.h"
54#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070055#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/object-inl.h"
58#include "mirror/object_array-inl.h"
59#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070060#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070062#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080063#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070064#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070065#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070066#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070067#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070068#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070069#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070070#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080071#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070072#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070073
74namespace art {
75
Ian Rogers00f7d0e2012-07-19 15:28:27 -070076static void ThrowNoClassDefFoundError(const char* fmt, ...)
77 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070078 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070079static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070080 va_list args;
81 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080082 Thread* self = Thread::Current();
83 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
84 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080085 va_end(args);
86}
87
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080088static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070090 // The class failed to initialize on a previous attempt, so we want to throw
91 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
92 // failed in verification, in which case v2 5.4.1 says we need to re-throw
93 // the previous error.
Ian Rogers7b078e82014-09-10 14:44:24 -070094 Runtime* runtime = Runtime::Current();
95 bool is_compiler = runtime->IsCompiler();
96 if (!is_compiler) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070097 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
98 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070099
Elliott Hughes5c599942012-06-13 16:45:05 -0700100 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800101 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700102 if (is_compiler) {
103 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
104 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
105 self->SetException(ThrowLocation(), pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700106 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700107 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
108 if (c->GetVerifyErrorClass() != NULL) {
109 // TODO: change the verifier to store an _instance_, with a useful detail message?
110 std::string temp;
111 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
112 PrettyDescriptor(c).c_str());
113 } else {
114 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
115 PrettyDescriptor(c).c_str());
116 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700117 }
118}
119
Brian Carlstromb23eab12014-10-08 17:55:21 -0700120static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
121 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
122 if (VLOG_IS_ON(class_linker)) {
123 std::string temp;
124 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
125 << klass->GetLocation() << "\n" << Thread::Current()->GetException(nullptr)->Dump();
126 }
127}
128
129static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
130 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700131 Thread* self = Thread::Current();
132 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700133
134 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700135 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700136
137 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700138 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
139 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700140
Elliott Hughesa4f94742012-05-29 16:28:38 -0700141 // We only wrap non-Error exceptions; an Error can just be used as-is.
142 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800143 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700144 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
145 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700146 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700147 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700148}
149
Fred Shih381e4ca2014-08-25 17:24:27 -0700150// Gap between two fields in object layout.
151struct FieldGap {
152 uint32_t start_offset; // The offset from the start of the object.
153 uint32_t size; // The gap size of 1, 2, or 4 bytes.
154};
155struct FieldGapsComparator {
156 explicit FieldGapsComparator() {
157 }
158 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
159 NO_THREAD_SAFETY_ANALYSIS {
160 // Sort by gap size, largest first.
161 return lhs.size > rhs.size;
162 }
163};
164typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
165
166// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800167static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700168 DCHECK(gaps != nullptr);
169
170 uint32_t current_offset = gap_start;
171 while (current_offset != gap_end) {
172 size_t remaining = gap_end - current_offset;
173 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
174 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
175 current_offset += sizeof(uint32_t);
176 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
177 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
178 current_offset += sizeof(uint16_t);
179 } else {
180 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
181 current_offset += sizeof(uint8_t);
182 }
183 DCHECK_LE(current_offset, gap_end) << "Overran gap";
184 }
185}
186// Shuffle fields forward, making use of gaps whenever possible.
187template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000188static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700189 MemberOffset* field_offset,
Fred Shih381e4ca2014-08-25 17:24:27 -0700190 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
191 FieldGaps* gaps)
192 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
193 DCHECK(current_field_idx != nullptr);
194 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700195 DCHECK(gaps != nullptr);
196 DCHECK(field_offset != nullptr);
197
198 DCHECK(IsPowerOfTwo(n));
199 while (!grouped_and_sorted_fields->empty()) {
200 mirror::ArtField* field = grouped_and_sorted_fields->front();
201 Primitive::Type type = field->GetTypeAsPrimitiveType();
202 if (Primitive::ComponentSize(type) < n) {
203 break;
204 }
205 if (!IsAligned<n>(field_offset->Uint32Value())) {
206 MemberOffset old_offset = *field_offset;
207 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
208 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
209 }
210 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
211 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700212 if (!gaps->empty() && gaps->top().size >= n) {
213 FieldGap gap = gaps->top();
214 gaps->pop();
215 DCHECK(IsAligned<n>(gap.start_offset));
216 field->SetOffset(MemberOffset(gap.start_offset));
217 if (gap.size > n) {
218 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
219 }
220 } else {
221 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
222 field->SetOffset(*field_offset);
223 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
224 }
225 ++(*current_field_idx);
226 }
227}
228
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800229ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700230 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700231 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700232 dex_cache_image_class_lookup_required_(false),
233 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800234 class_roots_(nullptr),
235 array_iftable_(nullptr),
236 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700237 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800238 log_new_dex_caches_roots_(false),
239 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700240 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800241 portable_resolution_trampoline_(nullptr),
242 quick_resolution_trampoline_(nullptr),
243 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800244 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100245 quick_generic_jni_trampoline_(nullptr),
246 quick_to_interpreter_bridge_trampoline_(nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -0800247 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700248}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700249
Alex Light64ad14d2014-08-19 14:23:13 -0700250void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800251 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700252 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700253
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700254 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700255
Elliott Hughes30646832011-10-13 16:59:46 -0700256 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700257 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700258 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700259 // 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 -0800260 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700261 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
262 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700263 heap->AllocNonMovableObject<true>(self, nullptr,
264 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700265 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700266 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700267 mirror::Class::SetClassClass(java_lang_Class.Get());
268 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700269 if (kUseBakerOrBrooksReadBarrier) {
270 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800271 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700272 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700273 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800274 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800275 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700276
Elliott Hughes418d20f2011-09-22 14:00:39 -0700277 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700278 Handle<mirror::Class> class_array_class(hs.NewHandle(
279 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700280 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700281
Ian Rogers23435d02012-09-24 11:23:12 -0700282 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700283 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
284 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700285 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700286 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700287 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700288 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700289
Ian Rogers23435d02012-09-24 11:23:12 -0700290 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700291 Handle<mirror::Class> object_array_class(hs.NewHandle(
292 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700293 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700294
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700295 // Setup the char (primitive) class to be used for char[].
296 Handle<mirror::Class> char_class(hs.NewHandle(
297 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700298 // The primitive char class won't be initialized by
299 // InitializePrimitiveClass until line 459, but strings (and
300 // internal char arrays) will be allocated before that and the
301 // component size, which is computed from the primitive type, needs
302 // to be set here.
303 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700304
Ian Rogers23435d02012-09-24 11:23:12 -0700305 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700306 Handle<mirror::Class> char_array_class(hs.NewHandle(
307 AllocClass(self, java_lang_Class.Get(),
308 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700309 char_array_class->SetComponentType(char_class.Get());
310 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700311
Ian Rogers23435d02012-09-24 11:23:12 -0700312 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700313 Handle<mirror::Class> java_lang_String(hs.NewHandle(
314 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700315 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700316 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700317 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400318
Fred Shih4ee7a662014-07-11 09:59:27 -0700319 // Setup Reference.
320 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
321 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
322 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
323 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
324 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
325
Ian Rogers23435d02012-09-24 11:23:12 -0700326 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700327 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
328 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
329 kClassRootsMax));
330 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700331 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
332 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
333 SetClassRoot(kClassArrayClass, class_array_class.Get());
334 SetClassRoot(kObjectArrayClass, object_array_class.Get());
335 SetClassRoot(kCharArrayClass, char_array_class.Get());
336 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700337 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338
339 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700340 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
341 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
342 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
343 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
344 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
345 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
346 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
347 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348
Ian Rogers23435d02012-09-24 11:23:12 -0700349 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700350 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351
Ian Rogers23435d02012-09-24 11:23:12 -0700352 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700353 Handle<mirror::Class> int_array_class(hs.NewHandle(
354 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700356 mirror::IntArray::SetArrayClass(int_array_class.Get());
357 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700359 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700360
Ian Rogers52813c92012-10-11 11:50:38 -0700361 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700362 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
363 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700364 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700365 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700366 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700367
Brian Carlstromf3632832014-05-20 15:36:53 -0700368 // Constructor, Field, Method, and AbstractMethod are necessary so
369 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700370 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
371 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700372 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700373 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700374 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700375 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700376 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700377
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700378 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
379 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700380 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700381 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700382 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700383 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700384
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700385 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700386
387 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700388 Handle<mirror::Class> object_array_string(hs.NewHandle(
389 AllocClass(self, java_lang_Class.Get(),
390 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700391 object_array_string->SetComponentType(java_lang_String.Get());
392 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700393
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700394 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
395 AllocClass(self, java_lang_Class.Get(),
396 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700397 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
398 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700399
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700400 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
401 AllocClass(self, java_lang_Class.Get(),
402 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700403 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
404 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700405
Ian Rogers23435d02012-09-24 11:23:12 -0700406 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
407 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
408 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700409 CHECK_NE(0U, boot_class_path.size());
410 for (size_t i = 0; i != boot_class_path.size(); ++i) {
411 const DexFile* dex_file = boot_class_path[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700412 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700413 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700414 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700415
416 // now we can use FindSystemClass
417
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700418 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700419 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
420 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700421
Jeff Hao88474b42013-10-23 16:24:40 -0700422 // Create runtime resolution and imt conflict methods. Also setup the default imt.
423 Runtime* runtime = Runtime::Current();
424 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
425 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700426 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700427 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
428
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700429 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
430 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700431 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700432 if (!runtime->IsCompiler()) {
433 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700434 quick_resolution_trampoline_ = GetQuickResolutionStub();
435 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
436 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700437 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700438
Mathieu Chartier66f19252012-09-18 08:57:04 -0700439 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700440 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800441 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700442 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700443 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700444 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800445 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700446 std::ostringstream os1, os2;
447 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
448 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
449 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
450 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700451 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800452 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700453 CHECK_EQ(java_lang_String.Get(), String_class);
454 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700455 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700456
Ian Rogers23435d02012-09-24 11:23:12 -0700457 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800458 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800459 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700460
Ian Rogers98379392014-02-24 16:53:16 -0800461 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800462 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700463
Ian Rogers98379392014-02-24 16:53:16 -0800464 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700465 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700466
Ian Rogers98379392014-02-24 16:53:16 -0800467 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800468 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700469
Ian Rogers98379392014-02-24 16:53:16 -0800470 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700471 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700472
Ian Rogers98379392014-02-24 16:53:16 -0800473 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800474 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475
Ian Rogers98379392014-02-24 16:53:16 -0800476 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800477 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700478
Ian Rogers98379392014-02-24 16:53:16 -0800479 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800480 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700481
Ian Rogers98379392014-02-24 16:53:16 -0800482 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700483 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700484
Ian Rogers98379392014-02-24 16:53:16 -0800485 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700486 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700487
Ian Rogers23435d02012-09-24 11:23:12 -0700488 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800489 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700490 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800491 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700492 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700493 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
494 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700495 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700496 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700497 array_iftable->SetInterface(0, java_lang_Cloneable);
498 array_iftable->SetInterface(1, java_io_Serializable);
499 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700500
Ian Rogers23435d02012-09-24 11:23:12 -0700501 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700502 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
503 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
504 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
505 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700506 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700507 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800508 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700509 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700510
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700511 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800512 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700513 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700514
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700515 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800516 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700517 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700518
Brian Carlstromf3632832014-05-20 15:36:53 -0700519 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700520 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700521 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700522
Brian Carlstromea46f952013-07-30 01:26:50 -0700523 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700524 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700525 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700526
Brian Carlstromea46f952013-07-30 01:26:50 -0700527 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700528 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700529 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700530
Ian Rogers23435d02012-09-24 11:23:12 -0700531 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700532
Ian Rogers23435d02012-09-24 11:23:12 -0700533 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800534 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700535 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
536
Brian Carlstrom1f870082011-08-23 16:02:11 -0700537 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700538 // finish initializing Reference class
539 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
540 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
541 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
542 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
543 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700544 mirror::Class* java_lang_ref_FinalizerReference =
545 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700546 java_lang_ref_FinalizerReference->SetAccessFlags(
547 java_lang_ref_FinalizerReference->GetAccessFlags() |
548 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700549 mirror::Class* java_lang_ref_PhantomReference =
550 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700551 java_lang_ref_PhantomReference->SetAccessFlags(
552 java_lang_ref_PhantomReference->GetAccessFlags() |
553 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700554 mirror::Class* java_lang_ref_SoftReference =
555 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700556 java_lang_ref_SoftReference->SetAccessFlags(
557 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700558 mirror::Class* java_lang_ref_WeakReference =
559 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700560 java_lang_ref_WeakReference->SetAccessFlags(
561 java_lang_ref_WeakReference->GetAccessFlags() |
562 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700563
Ian Rogers23435d02012-09-24 11:23:12 -0700564 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800565 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700566 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700567 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
568
jeffhao8cd6dda2012-02-22 10:15:34 -0800569 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700570 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800571 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800572 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700573 SetClassRoot(kJavaLangClassNotFoundException,
574 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800575 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700576 SetClassRoot(kJavaLangStackTraceElementArrayClass,
577 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800578 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700579
Ian Rogers98379392014-02-24 16:53:16 -0800580 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700581
Brian Carlstroma004aa92012-02-08 18:05:09 -0800582 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700583}
584
Ian Rogers98379392014-02-24 16:53:16 -0800585void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800586 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700587
588 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700589 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700590 // as the types of the field can't be resolved prior to the runtime being
591 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800592 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700593 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800594 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800595
Brian Carlstromea46f952013-07-30 01:26:50 -0700596 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700597 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
598 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700599
Brian Carlstromea46f952013-07-30 01:26:50 -0700600 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700601 CHECK_STREQ(queue->GetName(), "queue");
602 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700603
Brian Carlstromea46f952013-07-30 01:26:50 -0700604 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700605 CHECK_STREQ(queueNext->GetName(), "queueNext");
606 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700607
Brian Carlstromea46f952013-07-30 01:26:50 -0700608 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700609 CHECK_STREQ(referent->GetName(), "referent");
610 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700611
Brian Carlstromea46f952013-07-30 01:26:50 -0700612 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700613 CHECK_STREQ(zombie->GetName(), "zombie");
614 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700615
Brian Carlstroma663ea52011-08-19 23:33:41 -0700616 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700617 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700618 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800619 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700620 CHECK(klass != nullptr);
621 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700622 // note SetClassRoot does additional validation.
623 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700624 }
625
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700626 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700627
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700628 // disable the slow paths in FindClass and CreatePrimitiveClass now
629 // that Object, Class, and Object[] are setup
630 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700631
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800632 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700633}
634
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700635void ClassLinker::RunRootClinits() {
636 Thread* self = Thread::Current();
637 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800638 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700639 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700640 StackHandleScope<1> hs(self);
641 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700642 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700643 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700644 }
645 }
646}
647
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700648bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800649 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000650 const char* oat_cache_filename,
651 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700652 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700653 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800654
Ian Rogers1d54e732013-05-02 21:10:01 -0700655 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800656 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700657 if (heap->GetImageSpace() == nullptr) {
658 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
659 // out of space anyway it might not matter.
660 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
661 "without an image.", dex_filename);
662 return false;
663 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700664 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800665
Brian Carlstrom6449c622014-02-10 23:48:36 -0800666 std::string dex_file_option("--dex-file=");
667 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800668
Brian Carlstrom6449c622014-02-10 23:48:36 -0800669 std::string oat_fd_option("--oat-fd=");
670 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800671
Brian Carlstrom6449c622014-02-10 23:48:36 -0800672 std::string oat_location_option("--oat-location=");
673 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800674
Brian Carlstrom6449c622014-02-10 23:48:36 -0800675 std::vector<std::string> argv;
676 argv.push_back(dex2oat);
677 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800678 argv.push_back("-classpath");
679 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800680 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800681
Ian Rogers8afeb852014-04-02 14:55:49 -0700682 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800683
Jeff Hao4a200f52014-04-01 14:58:49 -0700684 if (!Runtime::Current()->IsVerificationEnabled()) {
685 argv.push_back("--compiler-filter=verify-none");
686 }
687
Alex Light6e183f22014-07-18 14:57:04 -0700688 if (Runtime::Current()->MustRelocateIfPossible()) {
689 argv.push_back("--runtime-arg");
690 argv.push_back("-Xrelocate");
691 } else {
692 argv.push_back("--runtime-arg");
693 argv.push_back("-Xnorelocate");
694 }
695
Brian Carlstrom6449c622014-02-10 23:48:36 -0800696 if (!kIsTargetBuild) {
697 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700698 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700699
Brian Carlstrom6449c622014-02-10 23:48:36 -0800700 argv.push_back(boot_image_option);
701 argv.push_back(dex_file_option);
702 argv.push_back(oat_fd_option);
703 argv.push_back(oat_location_option);
704 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800705 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800706 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700707 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800708
709 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700710}
711
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700712const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700713 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800714 if (kIsDebugBuild) {
715 for (size_t i = 0; i < oat_files_.size(); ++i) {
716 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700717 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800718 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700719 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
720 oat_files_.push_back(oat_file);
721 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800722}
723
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700724OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
725 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700726 OatFile* oat_file = space->ReleaseOatFile();
727 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700728 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700729 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700730}
731
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100732const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800733 const char* dex_location = dex_file.GetLocation().c_str();
734 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100735 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800736}
737
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100738const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
739 const char* dex_location,
740 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700741 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100742 for (const OatFile* oat_file : oat_files_) {
743 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700744
745 if (oat_location != nullptr) {
746 if (oat_file->GetLocation() != oat_location) {
747 continue;
748 }
749 }
750
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700751 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800752 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700753 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100754 if (oat_dex_file != nullptr) {
755 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800756 }
757 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100758 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800759}
760
Calin Juravle621962a2014-09-02 15:53:55 +0100761
762// Loads all multi dex files from the given oat file returning true on success.
763//
764// Parameters:
765// oat_file - the oat file to load from
766// dex_location - the dex location used to generate the oat file
767// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
768// generated - whether or not the oat_file existed before or was just (re)generated
769// error_msgs - any error messages will be appended here
770// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
771static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
772 const char* dex_location,
773 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700774 bool generated,
775 std::vector<std::string>* error_msgs,
776 std::vector<const DexFile*>* dex_files) {
777 if (oat_file == nullptr) {
778 return false;
779 }
780
781 size_t old_size = dex_files->size(); // To rollback on error.
782
783 bool success = true;
784 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100785 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700786 const char* next_name = next_name_str.c_str();
787
Calin Juravle621962a2014-09-02 15:53:55 +0100788 uint32_t next_location_checksum;
789 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700790 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100791 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
792 // When i=0 the multidex name should be the same as the location name. We already have the
793 // checksum it so we don't need to recompute it.
794 if (dex_location_checksum == nullptr) {
795 next_location_checksum_pointer = nullptr;
796 } else {
797 next_location_checksum = *dex_location_checksum;
798 }
799 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700800 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100801 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700802 }
803
804 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
805
806 if (oat_dex_file == nullptr) {
807 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700808 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100809 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700810 oat_file->GetLocation().c_str());
811 error_msgs->push_back(error_msg);
812 }
813 break; // Not found, done.
814 }
815
816 // Checksum test. Test must succeed when generated.
817 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100818 if (next_location_checksum_pointer != nullptr) {
819 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700820 }
821
822 if (success) {
823 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
824 if (dex_file == nullptr) {
825 success = false;
826 error_msgs->push_back(error_msg);
827 } else {
828 dex_files->push_back(dex_file);
829 }
830 }
831
832 // When we generated the file, we expect success, or something is terribly wrong.
833 CHECK_EQ(false, generated && !success)
834 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100835 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700836 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
837 }
838
839 if (dex_files->size() == old_size) {
840 success = false; // We did not even find classes.dex
841 }
842
843 if (success) {
844 return true;
845 } else {
846 // Free all the dex files we have loaded.
847 auto it = dex_files->begin() + old_size;
848 auto it_end = dex_files->end();
849 for (; it != it_end; it++) {
850 delete *it;
851 }
852 dex_files->erase(dex_files->begin() + old_size, it_end);
853
854 return false;
855 }
856}
857
858// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
859// complicates the loading process, as we should not use an iterative loading process, because that
860// would register the oat file and dex files that come before the broken one. Instead, check all
861// multidex ahead of time.
862bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
863 std::vector<std::string>* error_msgs,
864 std::vector<const DexFile*>* dex_files) {
865 // 1) Check whether we have an open oat file.
866 // This requires a dex checksum, use the "primary" one.
867 uint32_t dex_location_checksum;
868 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
869 bool have_checksum = true;
870 std::string checksum_error_msg;
871 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100872 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700873 dex_location_checksum_pointer = nullptr;
874 have_checksum = false;
875 }
876
877 bool needs_registering = false;
878
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100879 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
880 dex_location_checksum_pointer);
881 std::unique_ptr<const OatFile> open_oat_file(
882 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700883
884 // 2) If we do not have an open one, maybe there's one on disk already.
885
886 // In case the oat file is not open, we play a locking game here so
887 // that if two different processes race to load and register or generate
888 // (or worse, one tries to open a partial generated file) we will be okay.
889 // This is actually common with apps that use DexClassLoader to work
890 // around the dex method reference limit and that have a background
891 // service running in a separate process.
892 ScopedFlock scoped_flock;
893
894 if (open_oat_file.get() == nullptr) {
895 if (oat_location != nullptr) {
896 // Can only do this if we have a checksum, else error.
897 if (!have_checksum) {
898 error_msgs->push_back(checksum_error_msg);
899 return false;
900 }
901
902 std::string error_msg;
903
904 // We are loading or creating one in the future. Time to set up the file lock.
905 if (!scoped_flock.Init(oat_location, &error_msg)) {
906 error_msgs->push_back(error_msg);
907 return false;
908 }
909
Alex Lighta59dd802014-07-02 16:28:08 -0700910 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700911 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
912 oat_location, &error_msg));
913
914 if (open_oat_file.get() == nullptr) {
915 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
916 dex_location, oat_location, error_msg.c_str());
917 VLOG(class_linker) << compound_msg;
918 error_msgs->push_back(compound_msg);
919 }
920 } else {
921 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100922 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700923 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
924 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100925 kRuntimeISA, error_msgs,
926 &obsolete_file_cleanup_failed));
927 // There's no point in going forward and eventually try to regenerate the
928 // file if we couldn't remove the obsolete one. Mostly likely we will fail
929 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100930 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
931 if (obsolete_file_cleanup_failed) {
932 return false;
933 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700934 }
935 needs_registering = true;
936 }
937
938 // 3) If we have an oat file, check all contained multidex files for our dex_location.
939 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100940 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
941 dex_location_checksum_pointer,
942 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700943 if (success) {
944 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
945 if (needs_registering) {
946 // We opened the oat file, so we must register it.
947 RegisterOatFile(oat_file);
948 }
Alex Light9dcc4572014-08-14 14:16:26 -0700949 // If the file isn't executable we failed patchoat but did manage to get the dex files.
950 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700951 } else {
952 if (needs_registering) {
953 // We opened it, delete it.
954 open_oat_file.reset();
955 } else {
956 open_oat_file.release(); // Do not delete open oat files.
957 }
958 }
959
960 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
961
962 // Need a checksum, fail else.
963 if (!have_checksum) {
964 error_msgs->push_back(checksum_error_msg);
965 return false;
966 }
967
968 // Look in cache location if no oat_location is given.
969 std::string cache_location;
970 if (oat_location == nullptr) {
971 // Use the dalvik cache.
972 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
973 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
974 oat_location = cache_location.c_str();
975 }
976
Alex Light64ad14d2014-08-19 14:23:13 -0700977 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700978 // Definitely need to lock now.
979 if (!scoped_flock.HasFile()) {
980 std::string error_msg;
981 if (!scoped_flock.Init(oat_location, &error_msg)) {
982 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700983 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700984 }
985 }
986
Alex Light64ad14d2014-08-19 14:23:13 -0700987 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +0100988 // Create the oat file.
989 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
990 oat_location, error_msgs));
991 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700992
993 // Failed, bail.
994 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +0100995 std::string error_msg;
996 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
997 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
998 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -0700999 return false;
1000 }
1001
1002 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001003 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1004 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001005 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001006 if (success) {
1007 RegisterOatFile(open_oat_file.release());
1008 return true;
1009 } else {
1010 return false;
1011 }
1012}
1013
1014const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1015 uint32_t dex_location_checksum,
1016 const char* oat_location,
1017 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001018 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001019 !Runtime::Current()->IsCompiler(),
1020 error_msg));
1021 if (oat_file.get() == nullptr) {
1022 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1023 error_msg->c_str());
1024 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001025 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001026 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001027 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1028 if (image_space != nullptr) {
1029 const ImageHeader& image_header = image_space->GetImageHeader();
1030 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1031 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1032 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1033 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1034 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1035 actual_image_oat_checksum);
1036 return nullptr;
1037 }
1038
1039 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1040 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1041 if (expected_image_oat_offset != actual_image_oat_offset) {
1042 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1043 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1044 actual_image_oat_offset);
1045 return nullptr;
1046 }
1047 int32_t expected_patch_delta = image_header.GetPatchDelta();
1048 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1049 if (expected_patch_delta != actual_patch_delta) {
1050 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1051 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1052 return nullptr;
1053 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001054 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001055
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001056 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1057 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001058 if (oat_dex_file == nullptr) {
1059 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1060 dex_location);
1061 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001062 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001063 uint32_t expected_dex_checksum = dex_location_checksum;
1064 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1065 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001066 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1067 "found 0x%x", oat_location, expected_dex_checksum,
1068 actual_dex_checksum);
1069 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001070 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001071 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1072 if (dex_file.get() != nullptr) {
1073 return oat_file.release();
1074 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001075 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001076 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001077}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001078
Andreas Gampe833a4852014-05-21 18:46:59 -07001079const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1080 int fd, const char* oat_location,
1081 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001082 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001083 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001084 std::string error_msg;
1085 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001086 CHECK(!error_msg.empty());
1087 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001088 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001089 }
Igor Murashkin46774762014-10-22 11:37:02 -07001090 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001091 !Runtime::Current()->IsCompiler(),
1092 &error_msg));
1093 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001094 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1095 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001096 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001097 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001098 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001099
1100 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001101}
1102
Alex Light6e183f22014-07-18 14:57:04 -07001103bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1104 const InstructionSet instruction_set) {
1105 Runtime* runtime = Runtime::Current();
1106 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001107 if (image_space == nullptr) {
1108 return false;
1109 }
Alex Light6e183f22014-07-18 14:57:04 -07001110 uint32_t image_oat_checksum = 0;
1111 if (instruction_set == kRuntimeISA) {
1112 const ImageHeader& image_header = image_space->GetImageHeader();
1113 image_oat_checksum = image_header.GetOatChecksum();
1114 } else {
1115 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1116 image_space->GetImageLocation().c_str(), instruction_set));
1117 image_oat_checksum = image_header->GetOatChecksum();
1118 }
1119 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1120}
1121
1122bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1123 const InstructionSet instruction_set,
1124 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001125 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001126 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001127 if (image_space == nullptr) {
1128 *error_msg = "No image space for verification against";
1129 return false;
1130 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001131
1132 // If the requested instruction set is the same as the current runtime,
1133 // we can use the checksums directly. If it isn't, we'll have to read the
1134 // image header from the image for the right instruction set.
1135 uint32_t image_oat_checksum = 0;
1136 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001137 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001138 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001139 const ImageHeader& image_header = image_space->GetImageHeader();
1140 image_oat_checksum = image_header.GetOatChecksum();
1141 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001142 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001143 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001144 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001145 image_space->GetImageLocation().c_str(), instruction_set));
1146 image_oat_checksum = image_header->GetOatChecksum();
1147 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001148 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001149 }
1150 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001151 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1152
1153 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1154 if (!oat_file->IsPic()) {
1155 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1156 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1157 }
Alex Light6e183f22014-07-18 14:57:04 -07001158 if (!ret) {
1159 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1160 oat_file->GetLocation().c_str(),
1161 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1162 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1163 oat_file->GetOatHeader().GetImagePatchDelta(),
1164 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1165 }
1166 return ret;
1167}
1168
1169bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1170 const char* dex_location,
1171 uint32_t dex_location_checksum,
1172 const InstructionSet instruction_set,
1173 std::string* error_msg) {
1174 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1175 return false;
1176 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001177
Brian Carlstromf3632832014-05-20 15:36:53 -07001178 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1179 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001180 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001181 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1182 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001183 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001184 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001185 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001186 oat_dex_file_in->GetDexFileLocation().c_str(),
1187 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001188 }
1189 return false;
1190 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001191
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001192 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001193 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001194}
1195
Alex Lighta59dd802014-07-02 16:28:08 -07001196bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1197 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001198 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001199 std::string* error_msg) {
1200 CHECK(oat_file != nullptr);
1201 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001202 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001203 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001204 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1205 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1206 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001207 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001208 if (oat_dex_file == nullptr) {
1209 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001210 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001211 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001212 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001213 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001214 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001215 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001216 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001217 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001218 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001219 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001220 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001221 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001222 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001223 }
Alex Lighta59dd802014-07-02 16:28:08 -07001224 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001225}
1226
Andreas Gampe833a4852014-05-21 18:46:59 -07001227const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001228 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001229 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001230 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001231 std::vector<std::string>* error_msgs,
1232 bool* obsolete_file_cleanup_failed) {
1233 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001234 bool already_opened = false;
1235 std::string dex_location_str(dex_location);
1236 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1237 &already_opened,
1238 obsolete_file_cleanup_failed,
1239 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001240 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001241 if (oat_file.get() == nullptr) {
1242 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1243 dex_location));
1244 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001245 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001246 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1247 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001248 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1249 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001250 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001251 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001252 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001253 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001254 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1255 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1256 "dex location '%s'. Image checksum incorrect.",
1257 oat_file->GetLocation().c_str(), dex_location));
1258 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001259 } else {
1260 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001261 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001262}
1263
Brian Carlstromae826982011-11-09 01:33:42 -08001264const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001265 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001266 for (size_t i = 0; i < oat_files_.size(); i++) {
1267 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001268 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001269 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001270 return oat_file;
1271 }
1272 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001273 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001274}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001275
Alex Lighta59dd802014-07-02 16:28:08 -07001276const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1277 InstructionSet isa,
1278 bool *already_opened,
1279 bool *obsolete_file_cleanup_failed,
1280 std::vector<std::string>* error_msgs) {
1281 // Find out if we've already opened the file
1282 const OatFile* ret = nullptr;
1283 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1284 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1285 if (ret != nullptr) {
1286 *already_opened = true;
1287 return ret;
1288 }
1289
1290 std::string dalvik_cache;
1291 bool have_android_data = false;
1292 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001293 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001294 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001295 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001296 std::string cache_filename;
1297 if (have_dalvik_cache) {
1298 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1299 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1300 if (ret != nullptr) {
1301 *already_opened = true;
1302 return ret;
1303 }
1304 } else {
1305 // If we need to relocate we should just place odex back where it started.
1306 cache_filename = odex_filename;
1307 }
1308
1309 ret = nullptr;
1310
1311 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1312 //
1313 // Now we do the following:
1314 // 1) Try and open the odex version
1315 // 2) If present, checksum-verified & relocated correctly return it
1316 // 3) Close the odex version to free up its address space.
1317 // 4) Try and open the cache version
1318 // 5) If present, checksum-verified & relocated correctly return it
1319 // 6) Close the cache version to free up its address space.
1320 // 7) If we should relocate:
1321 // a) If we have opened and checksum-verified the odex version relocate it to
1322 // 'cache_filename' and return it
1323 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1324 // it. This should not happen often (I think only the run-test's will hit this case).
1325 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1326 // this point.
1327 // 9) Return nullptr
1328
1329 *already_opened = false;
1330 const Runtime* runtime = Runtime::Current();
1331 CHECK(runtime != nullptr);
1332 bool executable = !runtime->IsCompiler();
1333
1334 std::string odex_error_msg;
1335 bool should_patch_system = false;
1336 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001337 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001338 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001339 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001340 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001341 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001342 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001343 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001344 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001345 &odex_checksum_verified,
1346 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001347 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001348 } else {
1349 if (odex_checksum_verified) {
1350 // We can just relocate
1351 should_patch_system = true;
1352 odex_error_msg = "Image Patches are incorrect";
1353 }
1354 if (odex_oat_file.get() != nullptr) {
1355 have_system_odex = true;
1356 }
Alex Lighta59dd802014-07-02 16:28:08 -07001357 }
1358 }
1359
Alex Lighta59dd802014-07-02 16:28:08 -07001360 std::string cache_error_msg;
1361 bool should_patch_cache = false;
1362 bool cache_checksum_verified = false;
1363 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001364 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001365 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001366 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001367 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001368 &cache_checksum_verified,
1369 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001370 return cache_oat_file.release();
1371 } else if (cache_checksum_verified) {
1372 // We can just relocate
1373 should_patch_cache = true;
1374 cache_error_msg = "Image Patches are incorrect";
1375 }
1376 } else if (have_android_data) {
1377 // dalvik_cache does not exist but android data does. This means we should be able to create
1378 // it, so we should try.
1379 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1380 }
1381
1382 ret = nullptr;
1383 std::string error_msg;
1384 if (runtime->CanRelocate()) {
1385 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001386 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1387 if (space != nullptr) {
1388 const std::string& image_location = space->GetImageLocation();
1389 if (odex_checksum_verified && should_patch_system) {
1390 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1391 } else if (cache_checksum_verified && should_patch_cache) {
1392 CHECK(have_dalvik_cache);
1393 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1394 }
Alex Light84d76052014-08-22 17:49:35 -07001395 } else if (have_system_odex) {
1396 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001397 }
1398 }
1399 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1400 // implicitly: were able to fine where the cached version is but we were unable to use it,
1401 // either as a destination for relocation or to open a file. We should delete it if it is
1402 // there.
1403 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1404 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1405 "searching for dex file %s: %s",
1406 cache_filename.c_str(), dex_location.c_str(),
1407 strerror(errno));
1408 error_msgs->push_back(rm_error_msg);
1409 VLOG(class_linker) << rm_error_msg;
1410 // Let the caller know that we couldn't remove the obsolete file.
1411 // This is a good indication that further writes may fail as well.
1412 *obsolete_file_cleanup_failed = true;
1413 }
1414 }
1415 if (ret == nullptr) {
1416 VLOG(class_linker) << error_msg;
1417 error_msgs->push_back(error_msg);
1418 std::string relocation_msg;
1419 if (runtime->CanRelocate()) {
1420 relocation_msg = StringPrintf(" and relocation failed");
1421 }
1422 if (have_dalvik_cache && cache_checksum_verified) {
1423 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1424 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1425 cache_filename.c_str(), cache_error_msg.c_str(),
1426 relocation_msg.c_str());
1427 } else {
1428 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1429 "dalvik_cache availible)%s.", odex_filename.c_str(),
1430 odex_error_msg.c_str(), relocation_msg.c_str());
1431 }
1432 VLOG(class_linker) << error_msg;
1433 error_msgs->push_back(error_msg);
1434 }
1435 return ret;
1436}
1437
Alex Light9dcc4572014-08-14 14:16:26 -07001438const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1439 InstructionSet isa,
1440 std::string* error_msg) {
1441 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001442 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001443 if (output.get() == nullptr) {
1444 return nullptr;
1445 }
Alex Light84d76052014-08-22 17:49:35 -07001446 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1447 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001448 return output.release();
1449 } else {
1450 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1451 oat_path.c_str());
1452 return nullptr;
1453 }
1454}
1455
Alex Lighta59dd802014-07-02 16:28:08 -07001456const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1457 const std::string& output_oat,
1458 const std::string& image_location,
1459 InstructionSet isa,
1460 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001461 Runtime* runtime = Runtime::Current();
1462 DCHECK(runtime != nullptr);
1463 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001464 // We don't have an image space so there is no point in trying to patchoat.
1465 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1466 << "running without an image. Attempting to use oat file for interpretation.";
1467 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1468 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001469 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001470 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1471 // input_oat but make sure we only do interpretation on it's dex files.
1472 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1473 << "disabled. Attempting to use oat file for interpretation";
1474 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1475 }
Alex Lighta59dd802014-07-02 16:28:08 -07001476 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001477 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001478
1479 std::string isa_arg("--instruction-set=");
1480 isa_arg += GetInstructionSetString(isa);
1481 std::string input_oat_filename_arg("--input-oat-file=");
1482 input_oat_filename_arg += input_oat;
1483 std::string output_oat_filename_arg("--output-oat-file=");
1484 output_oat_filename_arg += output_oat;
1485 std::string patched_image_arg("--patched-image-location=");
1486 patched_image_arg += image_location;
1487
1488 std::vector<std::string> argv;
1489 argv.push_back(patchoat);
1490 argv.push_back(isa_arg);
1491 argv.push_back(input_oat_filename_arg);
1492 argv.push_back(output_oat_filename_arg);
1493 argv.push_back(patched_image_arg);
1494
1495 std::string command_line(Join(argv, ' '));
1496 LOG(INFO) << "Relocate Oat File: " << command_line;
1497 bool success = Exec(argv, error_msg);
1498 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001499 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001500 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001501 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001502 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1503 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001504 return output.release();
1505 } else if (output.get() != nullptr) {
1506 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1507 "but output file '%s' failed verifcation: %s",
1508 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1509 } else {
1510 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1511 "but was unable to open output file '%s': %s",
1512 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1513 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001514 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001515 // patchoat failed which means we probably don't have enough room to place the output oat file,
1516 // instead of failing we should just run the interpreter from the dex files in the input oat.
1517 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1518 << "for interpretation. patchoat failure was: " << *error_msg;
1519 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001520 } else {
1521 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1522 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1523 error_msg->c_str());
1524 }
1525 return nullptr;
1526}
1527
Andreas Gampe7ba64962014-10-23 11:37:40 -07001528bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001529 bool* checksum_verified,
1530 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001531 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001532 if (image_space == nullptr) {
1533 *error_msg = "No image space present";
1534 return false;
1535 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001536 uint32_t real_image_checksum;
1537 void* real_image_oat_offset;
1538 int32_t real_patch_delta;
1539 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001540 const ImageHeader& image_header = image_space->GetImageHeader();
1541 real_image_checksum = image_header.GetOatChecksum();
1542 real_image_oat_offset = image_header.GetOatDataBegin();
1543 real_patch_delta = image_header.GetPatchDelta();
1544 } else {
1545 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1546 image_space->GetImageLocation().c_str(), isa));
1547 real_image_checksum = image_header->GetOatChecksum();
1548 real_image_oat_offset = image_header->GetOatDataBegin();
1549 real_patch_delta = image_header->GetPatchDelta();
1550 }
1551
1552 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001553 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001554
1555 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1556 *checksum_verified = oat_image_checksum == real_image_checksum;
1557 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001558 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1559 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001560 }
1561
Andreas Gampe7ba64962014-10-23 11:37:40 -07001562 bool offset_verified;
1563 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001564
Andreas Gampe7ba64962014-10-23 11:37:40 -07001565 if (!oat_file->IsPic()) {
1566 // If an oat file is not PIC, we need to check that the image is at the expected location and
1567 // patched in the same way.
1568 void* oat_image_oat_offset =
1569 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1570 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1571 if (!offset_verified) {
1572 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1573 real_image_oat_offset, oat_image_oat_offset);
1574 }
1575
1576 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1577 patch_delta_verified = oat_patch_delta == real_patch_delta;
1578 if (!patch_delta_verified) {
1579 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1580 "received 0x%x)", real_patch_delta, oat_patch_delta);
1581 }
1582 } else {
1583 // If an oat file is PIC, we ignore offset and patching delta.
1584 offset_verified = true;
1585 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001586 }
1587
1588 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001589 if (!ret) {
1590 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001591 }
1592 return ret;
1593}
1594
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001595const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1596 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001597 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001598 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001599 return oat_file;
1600 }
1601
Igor Murashkin46774762014-10-22 11:37:02 -07001602 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001603 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001604}
1605
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001606static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001607 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001608 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1609
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001610 DCHECK(obj != nullptr);
1611 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001612
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001613 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001614 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001615 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001616 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers848871b2013-08-05 10:56:33 -07001617 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001618 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1619 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001620 }
1621 }
1622 }
1623}
1624
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001625void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001626 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001627 CHECK(!init_done_);
1628
Mathieu Chartier590fee92013-09-13 13:46:47 -07001629 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001630 gc::Heap* heap = Runtime::Current()->GetHeap();
1631 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001632 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001633 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001634 OatFile& oat_file = GetImageOatFile(space);
1635 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1636 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001637 const char* image_file_location = oat_file.GetOatHeader().
1638 GetStoreValueByKey(OatHeader::kImageLocationKey);
1639 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001640 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1641 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001642 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1643 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001644 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001645 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001646 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1647 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1648 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001649
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001650 StackHandleScope<1> hs(self);
1651 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1652 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1653 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001654 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001655
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001656 // Special case of setting up the String class early so that we can test arbitrary objects
1657 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001658 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001659
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001660 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001661 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001662 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001663 StackHandleScope<1> hs2(self);
1664 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001665 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001666 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1667 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001668 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001669 std::string error_msg;
1670 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001671 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001672 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001673 << " from within oat file " << oat_file.GetLocation()
1674 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001675 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001676
1677 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1678
1679 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001680 }
1681
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001682 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1683 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001684 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001685
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001686 // Set entry point to interpreter if in InterpretOnly mode.
1687 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001688 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001689 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001690 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001691
1692 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001693 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001694 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001695
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001696 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001697 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1698 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001699 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001700 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001701 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001702 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1703 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1704 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1705 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1706 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1707 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1708 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1709 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1710 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1711 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001712
Ian Rogers98379392014-02-24 16:53:16 -08001713 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001714
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001715 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001716}
1717
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001718void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1719 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1720 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001721 for (GcRoot<mirror::Class>& root : class_table_) {
1722 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1723 }
1724 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1725 root.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001726 }
1727 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001728 for (auto& root : new_class_roots_) {
1729 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
1730 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1731 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001732 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001733 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1734 // corresponding object. This is slow, but luckily for us, this may only happen with a
1735 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001736 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
1737 class_table_.Erase(it);
1738 class_table_.Insert(GcRoot<mirror::Class>(new_ref));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001739 }
1740 }
1741 }
1742 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1743 new_class_roots_.clear();
1744 }
1745 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1746 log_new_class_table_roots_ = true;
1747 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1748 log_new_class_table_roots_ = false;
1749 }
1750 // We deliberately ignore the class roots in the image since we
1751 // handle image roots by using the MS/CMS rescanning of dirty cards.
1752}
1753
Brian Carlstroma663ea52011-08-19 23:33:41 -07001754// Keep in sync with InitCallback. Anything we visit, we need to
1755// reinit references to when reinitializing a ClassLinker from a
1756// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001757void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001758 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001759 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001760 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001761 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001762 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001763 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1764 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001765 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001766 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1767 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001768 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001769 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001770 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001771 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1772 new_dex_cache_roots_.clear();
1773 }
1774 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1775 log_new_dex_caches_roots_ = true;
1776 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1777 log_new_dex_caches_roots_ = false;
1778 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001779 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001780 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001781 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1782 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001783 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001784 if (!find_array_class_cache_[i].IsNull()) {
1785 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001786 }
1787 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001788}
1789
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001790void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1791 if (dex_cache_image_class_lookup_required_) {
1792 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001793 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001794 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001795 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001796 for (GcRoot<mirror::Class>& root : class_table_) {
1797 if (!visitor(root.Read(), arg)) {
1798 return;
1799 }
1800 }
1801 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1802 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001803 return;
1804 }
1805 }
1806}
1807
Ian Rogersdbf3be02014-08-29 15:40:08 -07001808static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001809 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001810 classes->insert(c);
1811 return true;
1812}
1813
Ian Rogersdbf3be02014-08-29 15:40:08 -07001814struct GetClassesVisitorArrayArg {
1815 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1816 int32_t index;
1817 bool success;
1818};
1819
1820static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1821 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1822 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1823 if (arg->index < (*arg->classes)->GetLength()) {
1824 (*arg->classes)->Set(arg->index, c);
1825 arg->index++;
1826 return true;
1827 } else {
1828 arg->success = false;
1829 return false;
1830 }
1831}
1832
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001833void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001834 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1835 // is avoiding duplicates.
1836 if (!kMovingClasses) {
1837 std::set<mirror::Class*> classes;
1838 VisitClasses(GetClassesVisitorSet, &classes);
1839 for (mirror::Class* klass : classes) {
1840 if (!visitor(klass, arg)) {
1841 return;
1842 }
1843 }
1844 } else {
1845 Thread* self = Thread::Current();
1846 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001847 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001848 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1849 GetClassesVisitorArrayArg local_arg;
1850 local_arg.classes = &classes;
1851 local_arg.success = false;
1852 // We size the array assuming classes won't be added to the class table during the visit.
1853 // If this assumption fails we iterate again.
1854 while (!local_arg.success) {
1855 size_t class_table_size;
1856 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001857 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001858 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001859 }
1860 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1861 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1862 classes.Assign(
1863 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1864 CHECK(classes.Get() != nullptr); // OOME.
1865 local_arg.index = 0;
1866 local_arg.success = true;
1867 VisitClasses(GetClassesVisitorArray, &local_arg);
1868 }
1869 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1870 // If the class table shrank during creation of the clases array we expect null elements. If
1871 // the class table grew then the loop repeats. If classes are created after the loop has
1872 // finished then we don't visit.
1873 mirror::Class* klass = classes->Get(i);
1874 if (klass != nullptr && !visitor(klass, arg)) {
1875 return;
1876 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001877 }
1878 }
1879}
1880
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001881ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001882 mirror::Class::ResetClass();
1883 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001884 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001885 mirror::ArtField::ResetClass();
1886 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001887 mirror::BooleanArray::ResetArrayClass();
1888 mirror::ByteArray::ResetArrayClass();
1889 mirror::CharArray::ResetArrayClass();
1890 mirror::DoubleArray::ResetArrayClass();
1891 mirror::FloatArray::ResetArrayClass();
1892 mirror::IntArray::ResetArrayClass();
1893 mirror::LongArray::ResetArrayClass();
1894 mirror::ShortArray::ResetArrayClass();
1895 mirror::Throwable::ResetClass();
1896 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001897 STLDeleteElements(&boot_class_path_);
1898 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001899}
1900
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001901mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001902 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001903 StackHandleScope<16> hs(self);
1904 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1905 Handle<mirror::DexCache> dex_cache(
1906 hs.NewHandle(down_cast<mirror::DexCache*>(
1907 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1908 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001909 if (dex_cache.Get() == nullptr) {
1910 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001911 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001912 Handle<mirror::String>
1913 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001914 if (location.Get() == nullptr) {
1915 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001916 }
Ian Rogers700a4022014-05-19 16:49:03 -07001917 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001918 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001919 if (strings.Get() == nullptr) {
1920 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001921 }
Ian Rogers700a4022014-05-19 16:49:03 -07001922 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001923 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001924 if (types.Get() == nullptr) {
1925 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001926 }
Ian Rogers700a4022014-05-19 16:49:03 -07001927 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001928 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001929 if (methods.Get() == nullptr) {
1930 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001931 }
Ian Rogers700a4022014-05-19 16:49:03 -07001932 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001933 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001934 if (fields.Get() == nullptr) {
1935 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001936 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001937 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1938 fields.Get());
1939 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001940}
1941
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001942mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001943 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001944 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001945 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001946 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001947 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001948 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1949 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001950 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001951 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001952 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001953 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001954 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001955}
1956
Ian Rogers6fac4472014-02-25 17:01:10 -08001957mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001958 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001959}
1960
Brian Carlstromea46f952013-07-30 01:26:50 -07001961mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001962 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001963 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001964}
1965
Brian Carlstromea46f952013-07-30 01:26:50 -07001966mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001967 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001968 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001969}
1970
Mathieu Chartier590fee92013-09-13 13:46:47 -07001971mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1972 Thread* self, size_t length) {
1973 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1974 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001975}
1976
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001977mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1978 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001979 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001980
1981 // For temporary classes we must wait for them to be retired.
1982 if (init_done_ && klass->IsTemp()) {
1983 CHECK(!klass->IsResolved());
1984 if (klass->IsErroneous()) {
1985 ThrowEarlierClassFailure(klass);
1986 return nullptr;
1987 }
1988 StackHandleScope<1> hs(self);
1989 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1990 ObjectLock<mirror::Class> lock(self, h_class);
1991 // Loop and wait for the resolving thread to retire this class.
1992 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1993 lock.WaitIgnoringInterrupts();
1994 }
1995 if (h_class->IsErroneous()) {
1996 ThrowEarlierClassFailure(h_class.Get());
1997 return nullptr;
1998 }
1999 CHECK(h_class->IsRetired());
2000 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002001 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2002 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002003 }
2004
Brian Carlstromaded5f72011-10-07 17:15:04 -07002005 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002006 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002007 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002008 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2009 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002010 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002011 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2012 ThrowClassCircularityError(h_class.Get());
2013 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002014 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002015 }
2016 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002017 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002018 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002019 }
2020 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002021
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002022 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002023 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002024 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002025 }
2026 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002027 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002028 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002029 return klass;
2030}
2031
Ian Rogers68b56852014-08-29 20:19:11 -07002032typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2033
2034// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002035ClassPathEntry FindInClassPath(const char* descriptor,
2036 size_t hash, const std::vector<const DexFile*>& class_path) {
2037 for (const DexFile* dex_file : class_path) {
2038 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002039 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002040 return ClassPathEntry(dex_file, dex_class_def);
2041 }
2042 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002043 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002044}
2045
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002046mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2047 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002048 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002049 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002050 if (class_loader->GetClass() !=
2051 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2052 class_loader->GetParent()->GetClass() !=
2053 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2054 return nullptr;
2055 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002056 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002057 // Check if this would be found in the parent boot class loader.
2058 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002059 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002060 if (klass != nullptr) {
2061 return EnsureResolved(self, descriptor, klass);
2062 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002063 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002064 *pair.second);
2065 if (klass != nullptr) {
2066 return klass;
2067 }
2068 CHECK(self->IsExceptionPending()) << descriptor;
2069 self->ClearException();
2070 } else {
2071 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2072 StackHandleScope<3> hs(self);
2073 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2074 // We need to get the DexPathList and loop through it.
2075 Handle<mirror::ArtField> cookie_field =
2076 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2077 Handle<mirror::ArtField> dex_file_field =
2078 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002079 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002080 mirror::Object* dex_path_list =
2081 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2082 GetObject(class_loader.Get());
2083 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2084 cookie_field.Get() != nullptr) {
2085 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2086 mirror::Object* dex_elements_obj =
2087 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2088 GetObject(dex_path_list);
2089 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2090 // at the mCookie which is a DexFile vector.
2091 if (dex_elements_obj != nullptr) {
2092 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2093 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2094 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2095 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2096 if (element == nullptr) {
2097 // Should never happen, fall back to java code to throw a NPE.
2098 break;
2099 }
2100 mirror::Object* dex_file = dex_file_field->GetObject(element);
2101 if (dex_file != nullptr) {
2102 const uint64_t cookie = cookie_field->GetLong(dex_file);
2103 auto* dex_files =
2104 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2105 if (dex_files == nullptr) {
2106 // This should never happen so log a warning.
2107 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2108 break;
2109 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002110 for (const DexFile* cp_dex_file : *dex_files) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002111 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002112 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002113 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002114 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2115 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002116 if (klass == nullptr) {
2117 CHECK(self->IsExceptionPending()) << descriptor;
2118 self->ClearException();
2119 return nullptr;
2120 }
2121 return klass;
2122 }
2123 }
2124 }
2125 }
2126 }
2127 }
2128 }
2129 return nullptr;
2130}
2131
Ian Rogers98379392014-02-24 16:53:16 -08002132mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002133 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002134 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002135 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002136 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002137 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002138 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2139 // for primitive classes that aren't backed by dex files.
2140 return FindPrimitiveClass(descriptor[0]);
2141 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002142 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002143 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002144 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002145 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002146 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002147 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002148 // Class is not yet loaded.
2149 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002150 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002151 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002152 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002153 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002154 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002155 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002156 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002157 } else {
2158 // The boot class loader is searched ahead of the application class loader, failures are
2159 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2160 // trigger the chaining with a proper stack trace.
2161 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2162 self->SetException(ThrowLocation(), pre_allocated);
2163 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002164 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002165 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002166 // First try with the bootstrap class loader.
2167 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002168 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002169 if (klass != nullptr) {
2170 return EnsureResolved(self, descriptor, klass);
2171 }
2172 }
Ian Rogers63557452014-06-04 16:57:15 -07002173 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2174 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002175 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002176 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002177 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002178 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002179 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002180 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002181 const std::vector<const DexFile*>* class_path;
2182 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002183 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002184 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002185 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002186 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2187 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002188 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002189 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002190 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002191 } else {
2192 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2193 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2194 self->SetException(ThrowLocation(), pre_allocated);
2195 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002196 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002197 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002198 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002199 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2200 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002201 if (cp_klass != nullptr) {
2202 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002203 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002204 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002205 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002206 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002207 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002208 {
2209 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002210 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2211 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002212 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002213 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002214 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002215 }
Ian Rogers68b56852014-08-29 20:19:11 -07002216 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002217 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2218 WellKnownClasses::java_lang_ClassLoader_loadClass,
2219 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002220 }
Ian Rogers98379392014-02-24 16:53:16 -08002221 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002222 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002223 return nullptr;
2224 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002225 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002226 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002227 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002228 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002229 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002230 // success, return mirror::Class*
2231 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002232 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002233 }
Ian Rogers07140832014-09-30 15:43:59 -07002234 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002235}
2236
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002237mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002238 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002239 const DexFile& dex_file,
2240 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002241 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002242 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002243
Brian Carlstromaded5f72011-10-07 17:15:04 -07002244 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002245 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002246 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002247 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002248 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002249 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002250 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002251 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002252 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002253 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2254 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002255 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002256 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002257 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002258 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002259 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002260 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002261 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002262 }
2263
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002264 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002265 // Allocate a class with the status of not ready.
2266 // Interface object should get the right size here. Regular class will
2267 // figure out the right size later and be replaced with one of the right
2268 // size when the class becomes resolved.
2269 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002270 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002271 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002272 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002273 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002274 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002275 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002276 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002277 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002278 if (self->IsExceptionPending()) {
2279 // An exception occured during load, set status to erroneous while holding klass' lock in case
2280 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002281 if (!klass->IsErroneous()) {
2282 klass->SetStatus(mirror::Class::kStatusError, self);
2283 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002284 return nullptr;
2285 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002286 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002287
Mathieu Chartier590fee92013-09-13 13:46:47 -07002288 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002289 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002290 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002291 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2292 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002293 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002294 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002295
Brian Carlstromaded5f72011-10-07 17:15:04 -07002296 // Finish loading (if necessary) by finding parents
2297 CHECK(!klass->IsLoaded());
2298 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2299 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002300 if (!klass->IsErroneous()) {
2301 klass->SetStatus(mirror::Class::kStatusError, self);
2302 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002303 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002304 }
2305 CHECK(klass->IsLoaded());
2306 // Link the class (if necessary)
2307 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002308 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002309 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002310
2311 mirror::Class* new_class = nullptr;
2312 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002313 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002314 if (!klass->IsErroneous()) {
2315 klass->SetStatus(mirror::Class::kStatusError, self);
2316 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002317 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002318 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002319 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002320 CHECK(new_class != nullptr) << descriptor;
2321 CHECK(new_class->IsResolved()) << descriptor;
2322
2323 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002324
2325 /*
2326 * We send CLASS_PREPARE events to the debugger from here. The
2327 * definition of "preparation" is creating the static fields for a
2328 * class and initializing them to the standard default values, but not
2329 * executing any code (that comes later, during "initialization").
2330 *
2331 * We did the static preparation in LinkClass.
2332 *
2333 * The class has been prepared and resolved but possibly not yet verified
2334 * at this point.
2335 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002336 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002337
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002338 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002339}
2340
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002341uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2342 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002343 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002344 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002345 size_t num_8 = 0;
2346 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002347 size_t num_32 = 0;
2348 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002349 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002350 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2351 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002352 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002353 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002354 switch (c) {
2355 case 'L':
2356 case '[':
2357 num_ref++;
2358 break;
2359 case 'J':
2360 case 'D':
2361 num_64++;
2362 break;
2363 case 'I':
2364 case 'F':
2365 num_32++;
2366 break;
2367 case 'S':
2368 case 'C':
2369 num_16++;
2370 break;
2371 case 'B':
2372 case 'Z':
2373 num_8++;
2374 break;
2375 default:
2376 LOG(FATAL) << "Unknown descriptor: " << c;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002377 }
2378 }
2379 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002380 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002381}
2382
Ian Rogers97b52f82014-08-14 11:34:07 -07002383OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2384 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002385 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002386 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2387 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002388 *found = false;
2389 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002390 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002391 *found = true;
2392 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002393}
2394
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002395static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2396 uint32_t method_idx) {
2397 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002398 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002399 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002400 ClassDataItemIterator it(dex_file, class_data);
2401 // Skip fields
2402 while (it.HasNextStaticField()) {
2403 it.Next();
2404 }
2405 while (it.HasNextInstanceField()) {
2406 it.Next();
2407 }
2408 // Process methods
2409 size_t class_def_method_index = 0;
2410 while (it.HasNextDirectMethod()) {
2411 if (it.GetMemberIndex() == method_idx) {
2412 return class_def_method_index;
2413 }
2414 class_def_method_index++;
2415 it.Next();
2416 }
2417 while (it.HasNextVirtualMethod()) {
2418 if (it.GetMemberIndex() == method_idx) {
2419 return class_def_method_index;
2420 }
2421 class_def_method_index++;
2422 it.Next();
2423 }
2424 DCHECK(!it.HasNext());
2425 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2426 return 0;
2427}
2428
Ian Rogers97b52f82014-08-14 11:34:07 -07002429const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002430 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002431 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002432 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002433 size_t oat_method_index;
2434 if (method->IsStatic() || method->IsDirect()) {
2435 // Simple case where the oat method index was stashed at load time.
2436 oat_method_index = method->GetMethodIndex();
2437 } else {
2438 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2439 // by search for its position in the declared virtual methods.
2440 oat_method_index = declaring_class->NumDirectMethods();
2441 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002442 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002443 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002444 // Check method index instead of identity in case of duplicate method definitions.
2445 if (method->GetDexMethodIndex() ==
2446 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002447 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002448 break;
2449 }
Ian Rogersf320b632012-03-13 18:47:47 -07002450 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002451 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002452 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2453 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002454 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002455 DCHECK_EQ(oat_method_index,
2456 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002457 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002458 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002459 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2460 declaring_class->GetDexClassDefIndex(),
2461 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002462 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002463 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002464 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002465 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002466}
2467
2468// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002469const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002470 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002471 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002472 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002473 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002474 bool found;
2475 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002476 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002477 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002478 result = oat_method.GetQuickCode();
2479 }
2480
Ian Rogersef7d42f2014-01-06 12:55:46 -08002481 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002482 if (method->IsNative()) {
2483 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002484 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002485 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002486 // No code? Do we expect portable code?
2487 result = GetQuickToPortableBridge();
2488 } else {
2489 // No code? You must mean to go into the interpreter.
2490 result = GetQuickToInterpreterBridge();
2491 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002492 }
2493 return result;
TDYa12785321912012-04-01 15:24:56 -07002494}
2495
Ian Rogersef7d42f2014-01-06 12:55:46 -08002496const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2497 bool* have_portable_code) {
2498 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2499 *have_portable_code = false;
2500 if (method->IsProxyMethod()) {
2501 return GetPortableProxyInvokeHandler();
2502 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002503 bool found;
2504 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002505 const void* result = nullptr;
2506 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002507 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002508 result = oat_method.GetPortableCode();
2509 quick_code = oat_method.GetQuickCode();
2510 }
2511
Ian Rogersef7d42f2014-01-06 12:55:46 -08002512 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002513 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002514 // No code? You must mean to go into the interpreter.
2515 result = GetPortableToInterpreterBridge();
2516 } else {
2517 // No code? But there's quick code, so use a bridge.
2518 result = GetPortableToQuickBridge();
2519 }
2520 } else {
2521 *have_portable_code = true;
2522 }
2523 return result;
2524}
2525
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002526const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2527 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2528 return nullptr;
2529 }
2530 bool found;
2531 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2532 return found ? oat_method.GetQuickCode() : nullptr;
2533}
2534
2535const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2536 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2537 return nullptr;
2538 }
2539 bool found;
2540 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2541 return found ? oat_method.GetPortableCode() : nullptr;
2542}
2543
Ian Rogersef7d42f2014-01-06 12:55:46 -08002544const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2545 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002546 bool found;
2547 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2548 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002549 return nullptr;
2550 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002551 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002552 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002553}
2554
2555const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2556 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002557 bool found;
2558 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2559 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002560 return nullptr;
2561 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002562 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002563 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002564}
2565
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002566// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002567static bool NeedsInterpreter(
2568 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2569 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002570 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002571 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002572 // May return true for native code, in the case of generic JNI
2573 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002574 return true;
2575 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002576#ifdef ART_SEA_IR_MODE
2577 ScopedObjectAccess soa(Thread::Current());
2578 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2579 LOG(INFO) << "Found " << PrettyMethod(method);
2580 return false;
2581 }
2582#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002583 // If interpreter mode is enabled, every method (except native and proxy) must
2584 // be run with interpreter.
2585 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2586 !method->IsNative() && !method->IsProxyMethod();
2587}
2588
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002589void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002590 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002591 if (klass->NumDirectMethods() == 0) {
2592 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002593 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002594 Runtime* runtime = Runtime::Current();
2595 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002596 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2597 return; // OAT file unavailable.
2598 }
Ian Rogers19846512012-02-24 11:42:47 -08002599 }
Alex Light64ad14d2014-08-19 14:23:13 -07002600
Mathieu Chartierf8322842014-05-16 10:59:25 -07002601 const DexFile& dex_file = klass->GetDexFile();
2602 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002603 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002604 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002605 // There should always be class data if there were direct methods.
2606 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002607 ClassDataItemIterator it(dex_file, class_data);
2608 // Skip fields
2609 while (it.HasNextStaticField()) {
2610 it.Next();
2611 }
2612 while (it.HasNextInstanceField()) {
2613 it.Next();
2614 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002615 bool has_oat_class;
2616 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2617 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002618 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002619 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002620 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002621 if (!method->IsStatic()) {
2622 // Only update static methods.
2623 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002624 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002625 const void* portable_code = nullptr;
2626 const void* quick_code = nullptr;
2627 if (has_oat_class) {
2628 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2629 portable_code = oat_method.GetPortableCode();
2630 quick_code = oat_method.GetQuickCode();
2631 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002632 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2633 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002634 if (enter_interpreter) {
2635 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002636 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002637 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002638 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002639 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002640 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002641 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002642 quick_code = GetQuickToInterpreterBridge();
2643 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002644 } else {
2645 if (portable_code == nullptr) {
2646 portable_code = GetPortableToQuickBridge();
2647 } else {
2648 have_portable_code = true;
2649 }
2650 if (quick_code == nullptr) {
2651 quick_code = GetQuickToPortableBridge();
2652 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002653 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002654 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2655 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002656 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002657 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002658}
2659
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002660void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002661 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002662 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002663 Runtime* runtime = Runtime::Current();
2664 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002665 // The following code only applies to a non-compiler runtime.
2666 return;
2667 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002668 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002669 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2670 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002671 if (oat_class != nullptr) {
2672 // Every kind of method should at least get an invoke stub from the oat_method.
2673 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002674 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002675 oat_method.LinkMethod(method.Get());
2676 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002677
Jeff Hao16743632013-05-08 10:59:04 -07002678 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002679 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002680 method->GetEntryPointFromQuickCompiledCode(),
2681 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002682 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002683 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002684 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002685 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002686 }
2687
Brian Carlstrom92827a52011-10-10 15:50:01 -07002688 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002689 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2690 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002691 return;
2692 }
Ian Rogers19846512012-02-24 11:42:47 -08002693
Ian Rogersef7d42f2014-01-06 12:55:46 -08002694 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002695 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002696 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002697 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2698 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002699 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2700 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002701 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002702 if (!method->IsNative()) {
2703 // Set entry point from compiled code if there's no code or in interpreter only mode.
2704 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2705 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2706 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002707 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002708 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2709 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002710 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2711 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2712 have_portable_code = true;
2713 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2714 } else {
2715 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2716 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002717 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002718
Ian Rogers62d6c772013-02-27 08:32:07 -08002719 if (method->IsNative()) {
2720 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002721 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002722
2723 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002724 // We have a native method here without code. Then it should have either the generic JNI
2725 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2726 // TODO: this doesn't handle all the cases where trampolines may be installed.
2727 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2728 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002729 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002730 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002731
Ian Rogers62d6c772013-02-27 08:32:07 -08002732 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002733 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002734 method->GetEntryPointFromQuickCompiledCode(),
2735 method->GetEntryPointFromPortableCompiledCode(),
2736 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002737}
2738
Fred Shih37f05ef2014-07-16 18:38:08 -07002739
Fred Shih37f05ef2014-07-16 18:38:08 -07002740
Ian Rogers7b078e82014-09-10 14:44:24 -07002741void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002742 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002743 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002744 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002745 CHECK(klass.Get() != nullptr);
2746 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002747 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002748 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002749 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002750
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002751 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002752 if (kUseBakerOrBrooksReadBarrier) {
2753 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002754 }
Andreas Gampe51829322014-08-25 15:05:04 -07002755 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002756 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002757 klass->SetAccessFlags(access_flags);
2758 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002759 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002760 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002761
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002762 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002763 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002764
Ian Rogers13735952014-10-08 12:43:28 -07002765 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002766 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002767 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002768 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002769
Ian Rogers97b52f82014-08-14 11:34:07 -07002770
2771 bool has_oat_class = false;
2772 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2773 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2774 &has_oat_class);
2775 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002776 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002777 }
2778 }
2779 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002780 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002781 }
2782}
2783
Ian Rogers7b078e82014-09-10 14:44:24 -07002784void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002785 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002786 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002787 const OatFile::OatClass* oat_class) {
2788 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002789 ClassDataItemIterator it(dex_file, class_data);
2790 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002791 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002792 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002793 CHECK(self->IsExceptionPending()); // OOME.
2794 return;
2795 }
2796 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002797 }
2798 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002799 mirror::ObjectArray<mirror::ArtField>* fields =
2800 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002801 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002802 CHECK(self->IsExceptionPending()); // OOME.
2803 return;
2804 }
2805 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002806 }
2807 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002808 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002809 StackHandleScope<1> hs(self);
2810 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002811 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002812 CHECK(self->IsExceptionPending()); // OOME.
2813 return;
2814 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002815 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002816 LoadField(dex_file, it, klass, sfield);
2817 }
2818 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002819 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002820 StackHandleScope<1> hs(self);
2821 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002822 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002823 CHECK(self->IsExceptionPending()); // OOME.
2824 return;
2825 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002826 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002827 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002828 }
2829
Ian Rogers0571d352011-11-03 19:51:38 -07002830 // Load methods.
2831 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002832 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002833 mirror::ObjectArray<mirror::ArtMethod>* directs =
2834 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002835 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002836 CHECK(self->IsExceptionPending()); // OOME.
2837 return;
2838 }
2839 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002840 }
Ian Rogers0571d352011-11-03 19:51:38 -07002841 if (it.NumVirtualMethods() != 0) {
2842 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002843 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2844 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002845 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002846 CHECK(self->IsExceptionPending()); // OOME.
2847 return;
2848 }
2849 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002850 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002851 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002852 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2853 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002854 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002855 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002856 StackHandleScope<1> hs(self);
2857 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002858 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002859 CHECK(self->IsExceptionPending()); // OOME.
2860 return;
2861 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002862 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002863 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002864 uint32_t it_method_index = it.GetMemberIndex();
2865 if (last_dex_method_index == it_method_index) {
2866 // duplicate case
2867 method->SetMethodIndex(last_class_def_method_index);
2868 } else {
2869 method->SetMethodIndex(class_def_method_index);
2870 last_dex_method_index = it_method_index;
2871 last_class_def_method_index = class_def_method_index;
2872 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002873 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002874 }
2875 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002876 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002877 StackHandleScope<1> hs(self);
2878 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002879 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002880 CHECK(self->IsExceptionPending()); // OOME.
2881 return;
2882 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002883 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002884 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002885 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002886 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002887 }
2888 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002889}
2890
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002891void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002892 Handle<mirror::Class> klass,
2893 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002894 uint32_t field_idx = it.GetMemberIndex();
2895 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002896 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002897 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002898}
2899
Brian Carlstromea46f952013-07-30 01:26:50 -07002900mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002901 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002902 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002903 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002904 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002905 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002906
Brian Carlstromea46f952013-07-30 01:26:50 -07002907 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002908 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002909 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002910 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002911 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002912 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002913
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002914 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002915 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002916 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002917 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002918
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002919 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002920 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002921 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002922
Andreas Gampe51829322014-08-25 15:05:04 -07002923 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002924
Ian Rogersdfb325e2013-10-30 01:00:44 -07002925 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002926 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002927 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2928 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002929 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002930 klass->SetFinalizable();
2931 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002932 std::string temp;
2933 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002934 // The Enum class declares a "final" finalize() method to prevent subclasses from
2935 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2936 // subclasses, so we exclude it here.
2937 // We also want to avoid setting the flag on Object, where we know that finalize() is
2938 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002939 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2940 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002941 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002942 }
2943 }
2944 }
2945 } else if (method_name[0] == '<') {
2946 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002947 bool is_init = (strcmp("<init>", method_name) == 0);
2948 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002949 if (UNLIKELY(!is_init && !is_clinit)) {
2950 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2951 } else {
2952 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2953 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002954 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002955 access_flags |= kAccConstructor;
2956 }
2957 }
2958 }
2959 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002960
Mathieu Chartier66f19252012-09-18 08:57:04 -07002961 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002962}
2963
Ian Rogers7b078e82014-09-10 14:44:24 -07002964void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002965 StackHandleScope<1> hs(self);
2966 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002967 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2968 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002969 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002970}
2971
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002972void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002973 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002974 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002975 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002976 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002977}
2978
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002979bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002980 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002981 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002982 mirror::DexCache* dex_cache = GetDexCache(i);
2983 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002984 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002985 }
2986 }
2987 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002988}
2989
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002990bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002991 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002992 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002993}
2994
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002995void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002996 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002997 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002998 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002999 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3000 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003001 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003002 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003003 if (log_new_dex_caches_roots_) {
3004 // TODO: This is not safe if we can remove dex caches.
3005 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3006 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003007}
3008
Brian Carlstromaded5f72011-10-07 17:15:04 -07003009void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003010 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003011 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003012 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003013 if (IsDexFileRegisteredLocked(dex_file)) {
3014 return;
3015 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003016 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003017 // Don't alloc while holding the lock, since allocation may need to
3018 // suspend all threads and another thread may need the dex_lock_ to
3019 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003020 StackHandleScope<1> hs(self);
3021 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003022 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3023 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003024 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003025 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003026 if (IsDexFileRegisteredLocked(dex_file)) {
3027 return;
3028 }
3029 RegisterDexFileLocked(dex_file, dex_cache);
3030 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003031}
3032
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003033void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003034 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003035 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003036 RegisterDexFileLocked(dex_file, dex_cache);
3037}
3038
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003039mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003040 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003041 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003042 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003043 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003044 if (dex_cache->GetDexFile() == &dex_file) {
3045 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003046 }
3047 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003048 // Search matching by location name.
3049 std::string location(dex_file.GetLocation());
3050 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003051 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003052 if (dex_cache->GetDexFile()->GetLocation() == location) {
3053 return dex_cache;
3054 }
3055 }
3056 // Failure, dump diagnostic and abort.
3057 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003058 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003059 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3060 }
3061 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003062 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003063}
3064
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003065void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003066 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003067 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003068 mirror::DexCache* dex_cache = GetDexCache(i);
3069 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003070 }
3071}
3072
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003073mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003074 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003075 if (UNLIKELY(klass == nullptr)) {
3076 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003077 }
3078 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003079}
3080
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003081mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3082 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003083 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003084 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003085 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003086 StackHandleScope<1> hs(self);
3087 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003088 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003089 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003090 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003091 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3092 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003093 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3094 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003095 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003096 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003097}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003098
Brian Carlstrombe977852011-07-19 14:54:54 -07003099// Create an array class (i.e. the class object for the array, not the
3100// array itself). "descriptor" looks like "[C" or "[[[[B" or
3101// "[Ljava/lang/String;".
3102//
3103// If "descriptor" refers to an array of primitives, look up the
3104// primitive type's internally-generated class object.
3105//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003106// "class_loader" is the class loader of the class that's referring to
3107// us. It's used to ensure that we're looking for the element type in
3108// the right context. It does NOT become the class loader for the
3109// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003110//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003111// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003112mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003113 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003114 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003115 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003116 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003117 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3118 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003119 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003120 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003121 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003122 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3123 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003124 if (component_type.Get() == nullptr) {
3125 DCHECK(self->IsExceptionPending());
3126 return nullptr;
3127 } else {
3128 self->ClearException();
3129 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003130 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003131 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3132 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3133 return nullptr;
3134 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003135 // See if the component type is already loaded. Array classes are
3136 // always associated with the class loader of their underlying
3137 // element type -- an array of Strings goes with the loader for
3138 // java/lang/String -- so we need to look for it there. (The
3139 // caller should have checked for the existence of the class
3140 // before calling here, but they did so with *their* class loader,
3141 // not the component type's loader.)
3142 //
3143 // If we find it, the caller adds "loader" to the class' initiating
3144 // loader list, which should prevent us from going through this again.
3145 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003146 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003147 // are the same, because our caller (FindClass) just did the
3148 // lookup. (Even if we get this wrong we still have correct behavior,
3149 // because we effectively do this lookup again when we add the new
3150 // class to the hash table --- necessary because of possible races with
3151 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003152 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003153 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003154 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003155 return new_class;
3156 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003157 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003158
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003159 // Fill out the fields in the Class.
3160 //
3161 // It is possible to execute some methods against arrays, because
3162 // all arrays are subclasses of java_lang_Object_, so we need to set
3163 // up a vtable. We can just point at the one in java_lang_Object_.
3164 //
3165 // Array classes are simple enough that we don't need to do a full
3166 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003167 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003168 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003169 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003170 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003171 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003172 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003173 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003174 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003175 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003176 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003177 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003178 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003179 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003180 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003181 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003182 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003183 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003184 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003185 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003186 }
3187 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003188 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003189 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003190 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003191 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003192 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003193 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003194 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003195 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003196 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003197 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003198 new_class->SetSuperClass(java_lang_Object);
3199 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003200 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003201 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003202 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003203 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003204 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3205 Runtime::Current()->GetImtUnimplementedMethod());
3206 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003207 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003208 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003209 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003210 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003211
3212
3213 // All arrays have java/lang/Cloneable and java/io/Serializable as
3214 // interfaces. We need to set that up here, so that stuff like
3215 // "instanceof" works right.
3216 //
3217 // Note: The GC could run during the call to FindSystemClass,
3218 // so we need to make sure the class object is GC-valid while we're in
3219 // there. Do this by clearing the interface list so the GC will just
3220 // think that the entries are null.
3221
3222
3223 // Use the single, global copies of "interfaces" and "iftable"
3224 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003225 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003226 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003227 CHECK(array_iftable != nullptr);
3228 new_class->SetIfTable(array_iftable);
3229 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003230
Elliott Hughes00626c22013-06-14 15:04:14 -07003231 // Inherit access flags from the component type.
3232 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3233 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3234 access_flags &= kAccJavaFlagsMask;
3235 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003236 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003237 access_flags |= kAccAbstract | kAccFinal;
3238 access_flags &= ~kAccInterface;
3239
3240 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003241
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003242 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003243 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003244 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003245 }
3246 // Another thread must have loaded the class after we
3247 // started but before we finished. Abandon what we've
3248 // done.
3249 //
3250 // (Yes, this happens.)
3251
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003252 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003253}
3254
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003255mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003256 switch (type) {
3257 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003258 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003259 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003260 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003261 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003262 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003263 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003264 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003265 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003266 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003267 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003268 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003269 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003270 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003271 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003272 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003273 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003274 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003275 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003276 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003277 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003278 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003279 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003280 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003281}
3282
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003283mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3284 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003285 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003286 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003287 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003288 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003289 source += " from ";
3290 source += dex_cache->GetLocation()->ToModifiedUtf8();
3291 }
3292 LOG(INFO) << "Loaded class " << descriptor << source;
3293 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003294 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003295 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003296 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003297 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003298 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003299 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003300 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003301 // Check a class loaded with the system class loader matches one in the image if the class
3302 // is in the image.
3303 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003304 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003305 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003306 }
3307 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003308 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003309 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003310 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003311 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003312 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003313 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003314}
3315
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003316mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3317 size_t hash) {
3318 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003319 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3320 hash);
3321 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003322 CHECK(klass->IsProxyClass());
3323 return nullptr;
3324 }
3325
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003326 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003327 CHECK_NE(existing, klass) << descriptor;
3328 CHECK(!existing->IsResolved()) << descriptor;
3329 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3330
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003331 CHECK(!klass->IsTemp()) << descriptor;
3332 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3333 dex_cache_image_class_lookup_required_) {
3334 // Check a class loaded with the system class loader matches one in the image if the class
3335 // is in the image.
3336 existing = LookupClassFromImage(descriptor);
3337 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003338 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003339 }
3340 }
3341 VerifyObject(klass);
3342
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003343 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003344 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003345 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003346 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003347 }
3348
3349 return existing;
3350}
3351
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003352bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003353 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003354 auto pair = std::make_pair(descriptor, class_loader);
3355 auto it = class_table_.Find(pair);
3356 if (it != class_table_.end()) {
3357 class_table_.Erase(it);
3358 return true;
3359 }
3360 it = pre_zygote_class_table_.Find(pair);
3361 if (it != pre_zygote_class_table_.end()) {
3362 pre_zygote_class_table_.Erase(it);
3363 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003364 }
3365 return false;
3366}
3367
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003368mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003369 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003370 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003371 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003372 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003373 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003374 return result;
3375 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003376 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003377 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3378 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003379 } else {
3380 // Lookup failed but need to search dex_caches_.
3381 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003382 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003383 InsertClass(descriptor, result, hash);
3384 } else {
3385 // Searching the image dex files/caches failed, we don't want to get into this situation
3386 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3387 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003388 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003389 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3390 MoveImageClassesToClassTable();
3391 }
3392 }
3393 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003394 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003395}
3396
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003397mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003398 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003399 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003400 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3401 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3402 if (it == pre_zygote_class_table_.end()) {
3403 it = class_table_.FindWithHash(descriptor_pair, hash);
3404 if (it == class_table_.end()) {
3405 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003406 }
3407 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003408 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003409}
3410
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003411static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3412 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3413 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003414 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003415 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3416 return root->AsObjectArray<mirror::DexCache>();
3417}
3418
3419void ClassLinker::MoveImageClassesToClassTable() {
3420 Thread* self = Thread::Current();
3421 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3422 if (!dex_cache_image_class_lookup_required_) {
3423 return; // All dex cache classes are already in the class table.
3424 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003425 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003426 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003427 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003428 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3429 mirror::DexCache* dex_cache = dex_caches->Get(i);
3430 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3431 for (int32_t j = 0; j < types->GetLength(); j++) {
3432 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003433 if (klass != nullptr) {
3434 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003435 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003436 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003437 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3438 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003439 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003440 << PrettyClassAndClassLoader(klass);
3441 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003442 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003443 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003444 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003445 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003446 }
3447 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003448 }
3449 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003450 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003451}
3452
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003453void ClassLinker::MoveClassTableToPreZygote() {
3454 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3455 DCHECK(pre_zygote_class_table_.Empty());
3456 pre_zygote_class_table_ = std::move(class_table_);
3457 class_table_.Clear();
3458}
3459
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003460mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003461 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003462 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3463 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3464 mirror::DexCache* dex_cache = dex_caches->Get(i);
3465 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003466 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003467 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003468 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003469 const DexFile::TypeId* type_id =
3470 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003471 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003472 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3473 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003474 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003475 return klass;
3476 }
3477 }
3478 }
3479 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003480 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003481}
3482
3483void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3484 result.clear();
3485 if (dex_cache_image_class_lookup_required_) {
3486 MoveImageClassesToClassTable();
3487 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003488 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3489 while (true) {
3490 auto it = class_table_.Find(descriptor);
3491 if (it == class_table_.end()) {
3492 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003493 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003494 result.push_back(it->Read());
3495 class_table_.Erase(it);
3496 }
3497 for (mirror::Class* k : result) {
3498 class_table_.Insert(GcRoot<mirror::Class>(k));
3499 }
3500 size_t pre_zygote_start = result.size();
3501 // Now handle the pre zygote table.
3502 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3503 // called from the debugger.
3504 while (true) {
3505 auto it = pre_zygote_class_table_.Find(descriptor);
3506 if (it == pre_zygote_class_table_.end()) {
3507 break;
3508 }
3509 result.push_back(it->Read());
3510 pre_zygote_class_table_.Erase(it);
3511 }
3512 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3513 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003514 }
3515}
3516
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003517void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003518 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003519 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003520
Ian Rogers9ffb0392012-09-10 11:56:50 -07003521 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003522 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003523 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003524 return;
3525 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003526 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3527 return;
3528 }
jeffhao98eacac2011-09-14 16:11:53 -07003529
Ian Rogers9ffb0392012-09-10 11:56:50 -07003530 // The class might already be erroneous, for example at compile time if we attempted to verify
3531 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003532 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003533 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003534 return;
3535 }
3536
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003537 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003538 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003539 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003540 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003541 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003542 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003543 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003544 }
jeffhao98eacac2011-09-14 16:11:53 -07003545
Jeff Hao4a200f52014-04-01 14:58:49 -07003546 // Skip verification if disabled.
3547 if (!Runtime::Current()->IsVerificationEnabled()) {
3548 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003549 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003550 return;
3551 }
3552
Ian Rogers9ffb0392012-09-10 11:56:50 -07003553 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003554 StackHandleScope<2> hs(self);
3555 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003556 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003557 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003558 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003559
3560 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003561 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003562 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003563 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003564 std::string error_msg(
3565 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3566 PrettyDescriptor(klass.Get()).c_str(),
3567 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003568 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003569 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3570 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003571 self->ClearException();
3572 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003573 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3574 if (cause.Get() != nullptr) {
3575 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003576 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003577 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003578 if (Runtime::Current()->IsCompiler()) {
3579 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3580 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003581 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003582 return;
3583 }
3584 }
3585
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003586 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003587 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003588 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003589 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003590 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003591 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003592 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003593 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003594 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3595 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003596 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003597 return;
3598 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003599 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003600 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003601 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003602 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003603 Runtime::Current()->IsCompiler(),
3604 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003605 }
3606 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003607 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003608 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003609 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3610 << " because: " << error_msg;
3611 }
Ian Rogers1f539342012-10-03 21:09:42 -07003612 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003613 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003614 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003615 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003616 // Even though there were no verifier failures we need to respect whether the super-class
3617 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003618 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003619 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003620 } else {
3621 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003622 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003623 // Pretend a soft failure occured so that we don't consider the class verified below.
3624 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003625 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003626 } else {
3627 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3628 // Soft failures at compile time should be retried at runtime. Soft
3629 // failures at runtime will be handled by slow paths in the generated
3630 // code. Set status accordingly.
3631 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003632 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003633 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003634 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003635 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3636 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003637 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003638 }
3639 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003640 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003641 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003642 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3643 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003644 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003645 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003646 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003647 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003648 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003649 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003650 // Let the interpreter know it by setting the kAccPreverified flag onto each
3651 // method.
3652 // Note: we're going here during compilation and at runtime. When we set the
3653 // kAccPreverified flag when compiling image classes, the flag is recorded
3654 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003655 EnsurePreverifiedMethods(klass);
3656 }
3657}
3658
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003659void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003660 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003661 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003662 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003663 }
jeffhao98eacac2011-09-14 16:11:53 -07003664}
3665
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003666bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3667 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003668 // If we're compiling, we can only verify the class using the oat file if
3669 // we are not compiling the image or if the class we're verifying is not part of
3670 // the app. In other words, we will only check for preverification of bootclasspath
3671 // classes.
3672 if (Runtime::Current()->IsCompiler()) {
3673 // Are we compiling the bootclasspath?
3674 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3675 return false;
3676 }
3677 // We are compiling an app (not the image).
3678
3679 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003680 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003681 return false;
3682 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003683 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003684
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003685 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003686 // In case we run without an image there won't be a backing oat file.
3687 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003688 return false;
3689 }
3690
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003691 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003692 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003693 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3694 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003695 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003696 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003697 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003698 // Compile time verification failed with a soft error. Compile time verification can fail
3699 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003700 // class ... {
3701 // Foo x;
3702 // .... () {
3703 // if (...) {
3704 // v1 gets assigned a type of resolved class Foo
3705 // } else {
3706 // v1 gets assigned a type of unresolved class Bar
3707 // }
3708 // iput x = v1
3709 // } }
3710 // when we merge v1 following the if-the-else it results in Conflict
3711 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3712 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3713 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3714 // at compile time).
3715 return false;
3716 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003717 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003718 // Compile time verification failed with a hard error. This is caused by invalid instructions
3719 // in the class. These errors are unrecoverable.
3720 return false;
3721 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003722 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003723 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3724 // not loading the class.
3725 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3726 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003727 return false;
3728 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003729 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003730 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003731 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003732 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003733
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003734 return false;
3735}
3736
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003737void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003738 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003739 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3740 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3741 }
3742 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3743 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3744 }
3745}
3746
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003747void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003748 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003749 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3750 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003751 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003752 return; // native or abstract method
3753 }
3754 if (code_item->tries_size_ == 0) {
3755 return; // nothing to process
3756 }
Ian Rogers13735952014-10-08 12:43:28 -07003757 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003758 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3759 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3760 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3761 CatchHandlerIterator iterator(handlers_ptr);
3762 for (; iterator.HasNext(); iterator.Next()) {
3763 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3764 // unresolved exception types will be ignored by exception delivery
3765 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003766 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003767 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003768 DCHECK(Thread::Current()->IsExceptionPending());
3769 Thread::Current()->ClearException();
3770 }
3771 }
3772 }
3773 handlers_ptr = iterator.EndDataPointer();
3774 }
3775}
3776
Brian Carlstromea46f952013-07-30 01:26:50 -07003777static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003778static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3779 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003780
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003781mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003782 jobjectArray interfaces, jobject loader,
3783 jobjectArray methods, jobjectArray throws) {
3784 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003785 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003786 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003787 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003788 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003789 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003790 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003791 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003792 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003793 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003794 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3795 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003796 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003797 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003798 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003799 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003800 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003801 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003802
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003803 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003804 {
3805 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003806 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003807 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003808 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003809 }
3810 klass->SetSFields(sfields);
3811 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003812 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3813 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003814 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3815 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003816 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003817 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003818 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003819 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003820 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003821 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003822 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3823 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003824 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3825 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003826 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003827 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003828 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003829 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003830 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003831 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003832 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003833
Ian Rogers466bb252011-10-14 03:29:56 -07003834 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003835 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003836 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003837 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003838 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003839 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003840 }
3841 klass->SetDirectMethods(directs);
3842 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003843 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003844 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003845 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003846 }
3847 klass->SetDirectMethod(0, constructor);
3848 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003849
Mathieu Chartier590fee92013-09-13 13:46:47 -07003850 // Create virtual method using specified prototypes.
3851 size_t num_virtual_methods =
3852 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003853 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003854 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3855 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003856 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003857 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003858 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003859 }
3860 klass->SetVirtualMethods(virtuals);
3861 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003862 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003863 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003864 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3865 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003866 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003867 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003868 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003869 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003870 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003871 }
3872 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003873 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003874
3875 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003876 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003877 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003878
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003879 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3880 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003881 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003882 // Must hold lock on object when resolved.
3883 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003884 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003885 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003886 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003887 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003888 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003889 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003890 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003891 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003892
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003893 CHECK(klass->IsRetired());
3894 CHECK_NE(klass.Get(), new_class);
3895 klass.Assign(new_class);
3896
3897 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003898 interfaces_sfield->SetObject<false>(klass.Get(),
3899 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003900 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003901 throws_sfield->SetObject<false>(klass.Get(),
3902 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003903
3904 {
3905 // Lock on klass is released. Lock new class object.
3906 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003907 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003908 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003909
3910 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003911 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003912 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003913 CheckProxyConstructor(klass->GetDirectMethod(0));
3914 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003915 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003916 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3917 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003918 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3919 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003920 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003921 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003922
Mathieu Chartier590fee92013-09-13 13:46:47 -07003923 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003924 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003925 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003926 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3927
3928 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003929 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003930 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003931
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003932 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003933 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003934 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003935 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003936 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003937 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3938 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003939 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003940 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003941}
3942
Ian Rogersef7d42f2014-01-06 12:55:46 -08003943std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003944 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003945 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003946 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003947 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3948}
3949
Ian Rogersef7d42f2014-01-06 12:55:46 -08003950mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3951 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003952 DCHECK(proxy_class->IsProxyClass());
3953 DCHECK(proxy_method->IsProxyMethod());
3954 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003955 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003956 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003957 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003958 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003959 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003960 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003961 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003962 break;
3963 }
3964 }
3965 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003966 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003967 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003968 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003969 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003970 return resolved_method;
3971}
3972
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003973
Brian Carlstromea46f952013-07-30 01:26:50 -07003974mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003975 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003976 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003977 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003978 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003979 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003980 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3981 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003982 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3983 // constructor method.
3984 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3985 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003986 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3987 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003988 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3989 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003990 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003991 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003992 }
Ian Rogers466bb252011-10-14 03:29:56 -07003993 // Make this constructor public and fix the class to be our Proxy version
3994 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003995 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003996 return constructor;
3997}
3998
Brian Carlstromea46f952013-07-30 01:26:50 -07003999static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004000 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004001 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004002 CHECK_STREQ(constructor->GetName(), "<init>");
4003 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4004 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004005 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004006}
4007
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004008mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004009 Handle<mirror::Class> klass,
4010 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004011 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4012 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004013 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004014 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004015 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004016 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004017 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004018 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004019 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004020 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004021 }
Ian Rogers466bb252011-10-14 03:29:56 -07004022
4023 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4024 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004025 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004026 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004027
Ian Rogers466bb252011-10-14 03:29:56 -07004028 // At runtime the method looks like a reference and argument saving method, clone the code
4029 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004030 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4031 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004032 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004033
Ian Rogersc2b44472011-12-14 21:17:17 -08004034 return method;
4035}
Jesse Wilson95caa792011-10-12 18:14:17 -04004036
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004037static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4038 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004039 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004040 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004041 CHECK(!prototype->IsFinal());
4042 CHECK(method->IsFinal());
4043 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004044
4045 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4046 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4047 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004048 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4049 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004050 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4051
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004052 CHECK_STREQ(method->GetName(), prototype->GetName());
4053 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004054 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004055 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004056}
4057
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004058static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4059 bool can_init_parents)
4060 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004061 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004062 return true;
4063 }
4064 if (!can_init_statics) {
4065 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004066 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004067 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004068 return false;
4069 }
4070 // Check if there are encoded static values needing initialization.
4071 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004072 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004073 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004074 if (dex_class_def->static_values_off_ != 0) {
4075 return false;
4076 }
4077 }
4078 }
4079 if (!klass->IsInterface() && klass->HasSuperClass()) {
4080 mirror::Class* super_class = klass->GetSuperClass();
4081 if (!can_init_parents && !super_class->IsInitialized()) {
4082 return false;
4083 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004084 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004085 return false;
4086 }
4087 }
4088 }
4089 return true;
4090}
4091
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004092bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004093 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004094 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4095
4096 // Are we already initialized and therefore done?
4097 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4098 // an initialized class will never change its state.
4099 if (klass->IsInitialized()) {
4100 return true;
4101 }
4102
4103 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004104 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004105 return false;
4106 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004107
Ian Rogers7b078e82014-09-10 14:44:24 -07004108 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004109 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004110 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004111 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004112
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004113 // Re-check under the lock in case another thread initialized ahead of us.
4114 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004115 return true;
4116 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004117
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004118 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004119 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004120 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004121 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004122 return false;
4123 }
4124
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004125 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004126
4127 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004128 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004129 if (!klass->IsVerified()) {
4130 // We failed to verify, expect either the klass to be erroneous or verification failed at
4131 // compile time.
4132 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004133 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004134 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004135 } else {
4136 CHECK(Runtime::Current()->IsCompiler());
4137 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004138 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004139 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004140 } else {
4141 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004142 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004143 }
4144
Brian Carlstromd1422f82011-09-28 11:37:09 -07004145 // If the class is kStatusInitializing, either this thread is
4146 // initializing higher up the stack or another thread has beat us
4147 // to initializing and we need to wait. Either way, this
4148 // invocation of InitializeClass will not be responsible for
4149 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004150 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004151 // Could have got an exception during verification.
4152 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004153 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004154 return false;
4155 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004156 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004157 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004158 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004159 return true;
4160 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004161 // No. That's fine. Wait for another thread to finish initializing.
4162 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004163 }
4164
4165 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004166 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004167 return false;
4168 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004169 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004170
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004171 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004172
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004173 // From here out other threads may observe that we're initializing and so changes of state
4174 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004175 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004176 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004177
4178 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004179 }
4180
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004181 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004182 if (!klass->IsInterface() && klass->HasSuperClass()) {
4183 mirror::Class* super_class = klass->GetSuperClass();
4184 if (!super_class->IsInitialized()) {
4185 CHECK(!super_class->IsInterface());
4186 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004187 StackHandleScope<1> hs(self);
4188 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004189 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004190 if (!super_initialized) {
4191 // The super class was verified ahead of entering initializing, we should only be here if
4192 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004193 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004194 << "Super class initialization failed for "
4195 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004196 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004197 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004198 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004199 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004200 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004201 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004202 return false;
4203 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004204 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004205 }
4206
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004207 const size_t num_static_fields = klass->NumStaticFields();
4208 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004209 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004210 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004211 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004212 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004213 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004214 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004215
4216 // Eagerly fill in static fields so that the we don't have to do as many expensive
4217 // Class::FindStaticField in ResolveField.
4218 for (size_t i = 0; i < num_static_fields; ++i) {
4219 mirror::ArtField* field = klass->GetStaticField(i);
4220 const uint32_t field_idx = field->GetDexFieldIndex();
4221 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4222 if (resolved_field == nullptr) {
4223 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004224 } else {
4225 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004226 }
4227 }
4228
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004229 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4230 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004231 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004232 ClassDataItemIterator field_it(dex_file, class_data);
4233 if (value_it.HasNext()) {
4234 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004235 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004236 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004237 StackHandleScope<1> hs2(self);
4238 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004239 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004240 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004241 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004242 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004243 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004244 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004245 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004246 }
4247 }
4248 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004249
Ian Rogersd91d6d62013-09-25 20:26:14 -07004250 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004251 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004252 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004253 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004254 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004255 }
4256
Ian Rogers7b078e82014-09-10 14:44:24 -07004257 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004258 uint64_t t1 = NanoTime();
4259
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004260 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004261 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004262 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004263
4264 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004265 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004266 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004267 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004268 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004269 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4270 RuntimeStats* thread_stats = self->GetStats();
4271 ++global_stats->class_init_count;
4272 ++thread_stats->class_init_count;
4273 global_stats->class_init_time_ns += (t1 - t0);
4274 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004275 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004276 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004277 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004278 std::string temp;
4279 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004280 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004281 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004282 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004283 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004284 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004285 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004286 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004287}
4288
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004289bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004290 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004291 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004292 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004293 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004294 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004295 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004296
4297 // When we wake up, repeat the test for init-in-progress. If
4298 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004299 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004300 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004301 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004302 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004303 return false;
4304 }
4305 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004306 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004307 continue;
4308 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004309 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004310 // Compile time initialization failed.
4311 return false;
4312 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004313 if (klass->IsErroneous()) {
4314 // The caller wants an exception, but it was thrown in a
4315 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004316 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004317 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004318 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004319 return false;
4320 }
4321 if (klass->IsInitialized()) {
4322 return true;
4323 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004324 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004325 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004326 }
Ian Rogers07140832014-09-30 15:43:59 -07004327 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004328}
4329
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004330bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004331 if (klass->IsInterface()) {
4332 return true;
4333 }
Ian Rogers151f2212014-05-06 11:27:27 -07004334 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004335 Thread* self = Thread::Current();
4336 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004337 MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4338 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004339 if (klass->HasSuperClass() &&
4340 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004341 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4342 mh.ChangeMethod(klass->GetVTableEntry(i));
4343 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004344 if (mh.GetMethod() != super_mh.GetMethod() &&
Ian Rogersded66a02014-10-28 18:12:55 -07004345 !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004346 ThrowLinkageError(klass.Get(),
4347 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004348 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004349 PrettyMethod(mh.GetMethod()).c_str(),
4350 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004351 return false;
4352 }
4353 }
4354 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004355 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004356 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4357 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4358 for (uint32_t j = 0; j < num_methods; ++j) {
4359 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4360 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004361 if (mh.GetMethod() != super_mh.GetMethod() &&
Ian Rogersded66a02014-10-28 18:12:55 -07004362 !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004363 ThrowLinkageError(klass.Get(),
4364 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004365 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004366 PrettyMethod(mh.GetMethod()).c_str(),
4367 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004368 return false;
4369 }
4370 }
4371 }
4372 }
4373 return true;
4374}
4375
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004376bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4377 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004378 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004379 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004380 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004381 return true;
4382 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004383 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004384 if (!success) {
4385 if (can_init_fields && can_init_parents) {
4386 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4387 }
4388 } else {
4389 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004390 }
4391 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004392}
4393
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004394void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4395 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4396 if (fields != nullptr) {
4397 for (int index = 0; index < fields->GetLength(); index ++) {
4398 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4399 fields->Get(index)->SetDeclaringClass(new_class);
4400 }
4401 }
4402 }
4403
4404 fields = new_class->GetSFields();
4405 if (fields != nullptr) {
4406 for (int index = 0; index < fields->GetLength(); index ++) {
4407 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4408 fields->Get(index)->SetDeclaringClass(new_class);
4409 }
4410 }
4411 }
4412
4413 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4414 if (methods != nullptr) {
4415 for (int index = 0; index < methods->GetLength(); index ++) {
4416 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4417 methods->Get(index)->SetDeclaringClass(new_class);
4418 }
4419 }
4420 }
4421
4422 methods = new_class->GetVirtualMethods();
4423 if (methods != nullptr) {
4424 for (int index = 0; index < methods->GetLength(); index ++) {
4425 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4426 methods->Get(index)->SetDeclaringClass(new_class);
4427 }
4428 }
4429 }
4430}
4431
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004432bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4433 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004434 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004435 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004436
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004437 if (!LinkSuperClass(klass)) {
4438 return false;
4439 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004440 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4441 self, Runtime::Current()->GetImtUnimplementedMethod());
4442 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004443 return false;
4444 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004445 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004446 return false;
4447 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004448 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004449 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004450 return false;
4451 }
4452 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004453 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004454
4455 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4456 // We don't need to retire this class as it has no embedded tables or it was created the
4457 // correct size during class linker initialization.
4458 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4459
4460 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004461 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004462 }
4463
4464 // This will notify waiters on klass that saw the not yet resolved
4465 // class in the class_table_ during EnsureResolved.
4466 klass->SetStatus(mirror::Class::kStatusResolved, self);
4467 *new_class = klass.Get();
4468 } else {
4469 CHECK(!klass->IsResolved());
4470 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004471 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004472 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004473 CHECK(self->IsExceptionPending()); // Expect an OOME.
4474 klass->SetStatus(mirror::Class::kStatusError, self);
4475 return false;
4476 }
4477
4478 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4479 StackHandleScope<1> hs(self);
4480 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4481 ObjectLock<mirror::Class> lock(self, new_class_h);
4482
4483 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4484
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004485 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4486 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004487 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004488
4489 // This will notify waiters on temp class that saw the not yet resolved class in the
4490 // class_table_ during EnsureResolved.
4491 klass->SetStatus(mirror::Class::kStatusRetired, self);
4492
4493 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4494 // This will notify waiters on new_class that saw the not yet resolved
4495 // class in the class_table_ during EnsureResolved.
4496 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004497 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004498 return true;
4499}
4500
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004501bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004502 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004503 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4504 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004505 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004506 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004507 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004508 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004509 return false;
4510 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004511 // Verify
4512 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004513 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004514 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004515 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004516 return false;
4517 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004518 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004519 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004520 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004521 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004522 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004523 for (size_t i = 0; i < interfaces->Size(); i++) {
4524 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004525 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004526 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004527 DCHECK(Thread::Current()->IsExceptionPending());
4528 return false;
4529 }
4530 // Verify
4531 if (!klass->CanAccess(interface)) {
4532 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004533 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004534 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004535 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004536 return false;
4537 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004538 }
4539 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004540 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004541 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004542 return true;
4543}
4544
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004545bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004546 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004547 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004548 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004549 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004550 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004551 return false;
4552 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004553 return true;
4554 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004555 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004556 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4557 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004558 return false;
4559 }
4560 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004561 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004562 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004563 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004564 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004565 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004566 return false;
4567 }
4568 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004569 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004570 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004571 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004572 return false;
4573 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004574
Brian Carlstromf3632832014-05-20 15:36:53 -07004575 // Inherit kAccClassIsFinalizable from the superclass in case this
4576 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004577 if (super->IsFinalizable()) {
4578 klass->SetFinalizable();
4579 }
4580
Elliott Hughes2da50362011-10-10 16:57:08 -07004581 // Inherit reference flags (if any) from the superclass.
4582 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4583 if (reference_flags != 0) {
4584 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4585 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004586 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004587 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004588 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004589 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004590 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004591 return false;
4592 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004593
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004594 if (kIsDebugBuild) {
4595 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004596 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004597 CHECK(super->IsResolved());
4598 super = super->GetSuperClass();
4599 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004600 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004601 return true;
4602}
4603
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004604// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004605bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004606 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4607 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004608 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004609 if (klass->IsInterface()) {
4610 // No vtable.
4611 size_t count = klass->NumVirtualMethods();
4612 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004613 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004614 return false;
4615 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004616 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004617 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004618 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004619 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4620 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004621 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004622 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004623}
4624
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004625// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4626// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4627// caches in the implementation below.
4628class MethodNameAndSignatureComparator FINAL : public ValueObject {
4629 public:
4630 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4631 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4632 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4633 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004634 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4635 }
4636
4637 const char* GetName() {
4638 if (name_ == nullptr) {
4639 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4640 }
4641 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004642 }
4643
4644 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4645 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4646 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4647 const DexFile* other_dex_file = other->GetDexFile();
4648 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4649 if (dex_file_ == other_dex_file) {
4650 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4651 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004652 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004653 uint32_t other_name_len;
4654 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4655 &other_name_len);
4656 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4657 return false;
4658 }
4659 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4660 }
4661
4662 private:
4663 // Dex file for the method to compare against.
4664 const DexFile* const dex_file_;
4665 // MethodId for the method to compare against.
4666 const DexFile::MethodId* const mid_;
4667 // Lazily computed name from the dex file's strings.
4668 const char* name_;
4669 // Lazily computed name length.
4670 uint32_t name_len_;
4671};
4672
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004673class LinkVirtualHashTable {
4674 public:
4675 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4676 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4677 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4678 }
4679 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4680 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4681 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004682 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004683 uint32_t index = hash % hash_size_;
4684 // Linear probe until we have an empty slot.
4685 while (hash_table_[index] != invalid_index_) {
4686 if (++index == hash_size_) {
4687 index = 0;
4688 }
4689 }
4690 hash_table_[index] = virtual_method_index;
4691 }
4692 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4693 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4694 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004695 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004696 size_t index = hash % hash_size_;
4697 while (true) {
4698 const uint32_t value = hash_table_[index];
4699 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4700 // the block and can safely assume not found.
4701 if (value == invalid_index_) {
4702 break;
4703 }
4704 if (value != removed_index_) { // This signifies not already overriden.
4705 mirror::ArtMethod* virtual_method =
4706 klass_->GetVirtualMethodDuringLinking(value);
4707 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4708 hash_table_[index] = removed_index_;
4709 return value;
4710 }
4711 }
4712 if (++index == hash_size_) {
4713 index = 0;
4714 }
4715 }
4716 return GetNotFoundIndex();
4717 }
4718 static uint32_t GetNotFoundIndex() {
4719 return invalid_index_;
4720 }
4721
4722 private:
4723 static const uint32_t invalid_index_;
4724 static const uint32_t removed_index_;
4725
4726 Handle<mirror::Class> klass_;
4727 const size_t hash_size_;
4728 uint32_t* const hash_table_;
4729};
4730
4731const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4732const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4733
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004734bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004735 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004736 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004737 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4738 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004739 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004740 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004741 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004742 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4743 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4744 if (UNLIKELY(vtable.Get() == nullptr)) {
4745 CHECK(self->IsExceptionPending()); // OOME.
4746 return false;
4747 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004748 for (size_t i = 0; i < super_vtable_length; i++) {
4749 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004750 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004751 if (num_virtual_methods == 0) {
4752 klass->SetVTable(vtable.Get());
4753 return true;
4754 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004755 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004756 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4757 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4758 if (num_virtual_methods == 0) {
4759 klass->SetVTable(super_vtable);
4760 return true;
4761 }
4762 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004763 if (UNLIKELY(vtable.Get() == nullptr)) {
4764 CHECK(self->IsExceptionPending()); // OOME.
4765 return false;
4766 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004767 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004768 // How the algorithm works:
4769 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4770 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4771 // method which has not been matched to a vtable method, and j if the virtual method at the
4772 // index overrode the super virtual method at index j.
4773 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4774 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4775 // the need for the initial vtable which we later shrink back down).
4776 // 3. Add non overridden methods to the end of the vtable.
4777 static constexpr size_t kMaxStackHash = 250;
4778 const size_t hash_table_size = num_virtual_methods * 3;
4779 uint32_t* hash_table_ptr;
4780 std::unique_ptr<uint32_t[]> hash_heap_storage;
4781 if (hash_table_size <= kMaxStackHash) {
4782 hash_table_ptr = reinterpret_cast<uint32_t*>(
4783 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4784 } else {
4785 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4786 hash_table_ptr = hash_heap_storage.get();
4787 }
4788 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4789 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004790 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004791 hash_table.Add(i);
4792 }
4793 // Loop through each super vtable method and see if they are overriden by a method we added to
4794 // the hash table.
4795 for (size_t j = 0; j < super_vtable_length; ++j) {
4796 // Search the hash table to see if we are overidden by any method.
4797 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4798 MethodNameAndSignatureComparator super_method_name_comparator(
4799 super_method->GetInterfaceMethodIfProxy());
4800 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4801 if (hash_index != hash_table.GetNotFoundIndex()) {
4802 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4803 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4804 super_method->GetAccessFlags())) {
4805 if (super_method->IsFinal()) {
4806 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4807 PrettyMethod(virtual_method).c_str(),
4808 super_method->GetDeclaringClassDescriptor());
4809 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004810 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004811 vtable->SetWithoutChecks<false>(j, virtual_method);
4812 virtual_method->SetMethodIndex(j);
4813 } else {
4814 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004815 << " would have incorrectly overridden the package-private method in "
4816 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004817 }
4818 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004819 }
4820 // Add the non overridden methods at the end.
4821 size_t actual_count = super_vtable_length;
4822 for (size_t i = 0; i < num_virtual_methods; ++i) {
4823 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4824 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4825 if (method_idx < super_vtable_length &&
4826 local_method == vtable->GetWithoutChecks(method_idx)) {
4827 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004828 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004829 vtable->SetWithoutChecks<false>(actual_count, local_method);
4830 local_method->SetMethodIndex(actual_count);
4831 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004832 }
4833 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004834 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004835 return false;
4836 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004837 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004838 CHECK_LE(actual_count, max_count);
4839 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004840 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004841 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004842 CHECK(self->IsExceptionPending()); // OOME.
4843 return false;
4844 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004845 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004846 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004847 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004848 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004849 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004850 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4851 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004852 return false;
4853 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004854 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4855 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004856 CHECK(self->IsExceptionPending()); // OOME.
4857 return false;
4858 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004859 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004860 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004861 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004862 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004863 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004864 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004865 }
4866 return true;
4867}
4868
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004869bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4870 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4871 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004872 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004873 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004874 const bool has_superclass = klass->HasSuperClass();
4875 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4876 const bool have_interfaces = interfaces.Get() != nullptr;
4877 const size_t num_interfaces =
4878 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4879 if (num_interfaces == 0) {
4880 if (super_ifcount == 0) {
4881 // Class implements no interfaces.
4882 DCHECK_EQ(klass->GetIfTableCount(), 0);
4883 DCHECK(klass->GetIfTable() == nullptr);
4884 return true;
4885 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004886 // Class implements same interfaces as parent, are any of these not marker interfaces?
4887 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004888 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004889 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004890 if (super_iftable->GetMethodArrayCount(i) > 0) {
4891 has_non_marker_interface = true;
4892 break;
4893 }
4894 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004895 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004896 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004897 klass->SetIfTable(super_iftable);
4898 return true;
4899 }
4900 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004901 size_t ifcount = super_ifcount + num_interfaces;
4902 for (size_t i = 0; i < num_interfaces; i++) {
4903 mirror::Class* interface = have_interfaces ?
4904 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4905 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004906 if (UNLIKELY(!interface->IsInterface())) {
4907 std::string temp;
4908 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4909 PrettyDescriptor(klass.Get()).c_str(),
4910 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4911 return false;
4912 }
4913 ifcount += interface->GetIfTableCount();
4914 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004915 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004916 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004917 CHECK(self->IsExceptionPending()); // OOME.
4918 return false;
4919 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004920 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004921 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004922 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004923 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004924 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004925 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004926 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004927 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004928 // Flatten the interface inheritance hierarchy.
4929 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004930 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004931 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4932 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004933 // Check if interface is already in iftable
4934 bool duplicate = false;
4935 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004936 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004937 if (existing_interface == interface) {
4938 duplicate = true;
4939 break;
4940 }
4941 }
4942 if (!duplicate) {
4943 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004944 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004945 // Add this interface's non-duplicate super-interfaces.
4946 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004947 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004948 bool super_duplicate = false;
4949 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004950 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004951 if (existing_interface == super_interface) {
4952 super_duplicate = true;
4953 break;
4954 }
4955 }
4956 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004957 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004958 }
4959 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004960 }
4961 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004962 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004963 // Shrink iftable in case duplicates were found
4964 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004965 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004966 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004967 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004968 CHECK(self->IsExceptionPending()); // OOME.
4969 return false;
4970 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004971 ifcount = idx;
4972 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004973 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004974 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004975 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004976 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004977 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004978 return true;
4979 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004980 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004981 size_t max_miranda_methods = 0; // The max size of miranda_list.
4982 for (size_t i = 0; i < ifcount; ++i) {
4983 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4984 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004985 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004986 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004987 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4988 hs.NewHandle(klass->GetVTableDuringLinking()));
4989 // Copy the IMT from the super class if possible.
4990 bool extend_super_iftable = false;
4991 if (has_superclass) {
4992 mirror::Class* super_class = klass->GetSuperClass();
4993 extend_super_iftable = true;
4994 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4995 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4996 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4997 }
4998 } else {
4999 // No imt in the super class, need to reconstruct from the iftable.
5000 mirror::IfTable* if_table = super_class->GetIfTable();
5001 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5002 const size_t length = super_class->GetIfTableCount();
5003 for (size_t i = 0; i < length; ++i) {
5004 mirror::Class* interface = iftable->GetInterface(i);
5005 const size_t num_virtuals = interface->NumVirtualMethods();
5006 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5007 DCHECK_EQ(num_virtuals, method_array_count);
5008 if (method_array_count == 0) {
5009 continue;
5010 }
5011 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5012 for (size_t j = 0; j < num_virtuals; ++j) {
5013 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5014 if (method->IsMiranda()) {
5015 continue;
5016 }
5017 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5018 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5019 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5020 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5021 out_imt->SetReference(imt_index, method);
5022 } else if (imt_ref != conflict_method) {
5023 out_imt->SetReference(imt_index, conflict_method);
5024 }
5025 }
5026 }
5027 }
5028 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005029 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005030 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005031 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005032 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005033 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005034 const bool is_super = i < super_ifcount;
5035 const bool super_interface = is_super && extend_super_iftable;
5036 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5037 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5038 if (super_interface) {
5039 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5040 DCHECK(if_table != nullptr);
5041 DCHECK(if_table->GetMethodArray(i) != nullptr);
5042 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005043 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005044 AsObjectArray<mirror::ArtMethod>());
5045 // We are overwriting a super class interface, try to only virtual methods instead of the
5046 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005047 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005048 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005049 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005050 // A new interface, we need the whole vtable incase a new interface method is implemented
5051 // in the whole superclass.
5052 input_array = vtable;
5053 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005054 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005055 CHECK(self->IsExceptionPending()); // OOME.
5056 return false;
5057 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005058 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005059 if (input_array.Get() == nullptr) {
5060 // If the added virtual methods is empty, do nothing.
5061 DCHECK(super_interface);
5062 continue;
5063 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005064 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005065 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005066 MethodNameAndSignatureComparator interface_name_comparator(
5067 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005068 int32_t k;
5069 // For each method listed in the interface's method list, find the
5070 // matching method in our class's method list. We want to favor the
5071 // subclass over the superclass, which just requires walking
5072 // back from the end of the vtable. (This only matters if the
5073 // superclass defines a private method and this class redefines
5074 // it -- otherwise it would use the same vtable slot. In .dex files
5075 // those don't end up in the virtual method table, so it shouldn't
5076 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005077 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5078 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005079 mirror::ArtMethod* vtable_method_for_name_comparison =
5080 vtable_method->GetInterfaceMethodIfProxy();
5081 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005082 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005083 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005084 ThrowIllegalAccessError(
5085 klass.Get(),
5086 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005087 PrettyMethod(vtable_method).c_str(),
5088 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005089 return false;
5090 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005091 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005092 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005093 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5094 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5095 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5096 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5097 out_imt->SetReference(imt_index, vtable_method);
5098 } else if (imt_ref != conflict_method) {
5099 // If we are not a conflict and we have the same signature and name as the imt entry,
5100 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005101 MethodNameAndSignatureComparator imt_ref_name_comparator(
5102 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005103 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005104 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005105 out_imt->SetReference(imt_index, vtable_method);
5106 } else {
5107 out_imt->SetReference(imt_index, conflict_method);
5108 }
Jeff Hao88474b42013-10-23 16:24:40 -07005109 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005110 break;
5111 }
5112 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005113 if (k < 0 && !super_interface) {
5114 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005115 for (size_t l = 0; l < miranda_list_size; ++l) {
5116 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005117 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005118 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005119 break;
5120 }
5121 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005122 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005123 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005124 miranda_method = interface_method->Clone(self)->AsArtMethod();
5125 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005126 CHECK(self->IsExceptionPending()); // OOME.
5127 return false;
5128 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005129 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005130 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005131 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005132 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005133 }
5134 }
5135 }
5136 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005137 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005138 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005139 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005140 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5141 if (old_method_count == 0) {
5142 virtuals = AllocArtMethodArray(self, new_method_count);
5143 } else {
5144 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5145 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005146 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005147 CHECK(self->IsExceptionPending()); // OOME.
5148 return false;
5149 }
5150 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005151
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005152 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005153 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005154 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005155 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005156 CHECK(self->IsExceptionPending()); // OOME.
5157 return false;
5158 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005159 for (size_t i = 0; i < miranda_list_size; ++i) {
5160 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005161 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005162 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5163 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5164 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005165 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005166 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005167 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005168 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005169 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005170
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005171 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005172 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5173 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5174 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005175 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005176 }
5177
Ian Rogers7b078e82014-09-10 14:44:24 -07005178 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005179 return true;
5180}
5181
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005182bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005183 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005184 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005185}
5186
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005187bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005188 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005189 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005190}
5191
Brian Carlstromdbc05252011-09-09 01:59:59 -07005192struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005193 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5194 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005195 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005196 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005197 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005198 // 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 -07005199 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5200 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005201 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005202 if (type1 == Primitive::kPrimNot) {
5203 // Reference always goes first.
5204 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005205 }
Vladimir Markod5777482014-11-12 17:02:02 +00005206 if (type2 == Primitive::kPrimNot) {
5207 // Reference always goes first.
5208 return false;
5209 }
5210 size_t size1 = Primitive::ComponentSize(type1);
5211 size_t size2 = Primitive::ComponentSize(type2);
5212 if (size1 != size2) {
5213 // Larger primitive types go first.
5214 return size1 > size2;
5215 }
5216 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5217 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005218 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005219 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5220 // by name and for equal names by type id index.
5221 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5222 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005223 }
5224};
5225
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005226bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005227 size_t* class_size) {
5228 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005229 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005230 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005231
Brian Carlstromea46f952013-07-30 01:26:50 -07005232 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005233 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005234
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005235 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005236 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005237 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005238 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005239 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005240 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005241 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005242 CHECK(super_class->IsResolved())
5243 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005244 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005245 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005246 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005247
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005248 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005249
Brian Carlstromdbc05252011-09-09 01:59:59 -07005250 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005251 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005252 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005253 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005254 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005255 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005256 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005257 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005258 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005259 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005260 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5261 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005262
Fred Shih381e4ca2014-08-25 17:24:27 -07005263 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005264 size_t current_field = 0;
5265 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005266 FieldGaps gaps;
5267
Brian Carlstromdbc05252011-09-09 01:59:59 -07005268 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005269 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005270 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005271 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005272 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005273 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005274 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005275 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5276 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005277 MemberOffset old_offset = field_offset;
5278 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5279 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5280 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005281 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005282 grouped_and_sorted_fields.pop_front();
5283 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005284 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005285 field_offset = MemberOffset(field_offset.Uint32Value() +
5286 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005287 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005288 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5289 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005290 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5291 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5292 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5293 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005294 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5295 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005296 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005297
Elliott Hughesadb460d2011-10-05 17:02:34 -07005298 // 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 -07005299 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005300 // We know there are no non-reference fields in the Reference classes, and we know
5301 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005302 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005303 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005304 --num_reference_fields;
5305 }
5306
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005307 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005308 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005309 if (is_static) {
5310 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005311 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005312 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005313 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005314 if (!klass->IsVariableSize()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005315 std::string temp;
5316 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005317 size_t previous_size = klass->GetObjectSize();
5318 if (previous_size != 0) {
5319 // Make sure that we didn't originally have an incorrect size.
Ian Rogers1ff3c982014-08-12 02:30:58 -07005320 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005321 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005322 klass->SetObjectSize(size);
5323 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005324 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005325
5326 if (kIsDebugBuild) {
5327 // Make sure that the fields array is ordered by name but all reference
5328 // offsets are at the beginning as far as alignment allows.
5329 MemberOffset start_ref_offset = is_static
5330 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5331 : klass->GetFirstReferenceInstanceFieldOffset();
5332 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5333 num_reference_fields *
5334 sizeof(mirror::HeapReference<mirror::Object>));
5335 MemberOffset current_ref_offset = start_ref_offset;
5336 for (size_t i = 0; i < num_fields; i++) {
5337 mirror::ArtField* field = fields->Get(i);
5338 if ((false)) { // enable to debug field layout
5339 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5340 << " class=" << PrettyClass(klass.Get())
5341 << " field=" << PrettyField(field)
5342 << " offset="
5343 << field->GetField32(mirror::ArtField::OffsetOffset());
5344 }
5345 if (i != 0) {
5346 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005347 // NOTE: The field names can be the same. This is not possible in the Java language
5348 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5349 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005350 }
5351 Primitive::Type type = field->GetTypeAsPrimitiveType();
5352 bool is_primitive = type != Primitive::kPrimNot;
5353 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5354 strcmp("referent", field->GetName()) == 0) {
5355 is_primitive = true; // We lied above, so we have to expect a lie here.
5356 }
5357 MemberOffset offset = field->GetOffsetDuringLinking();
5358 if (is_primitive) {
5359 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5360 // Shuffled before references.
5361 size_t type_size = Primitive::ComponentSize(type);
5362 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5363 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5364 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5365 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5366 }
5367 } else {
5368 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5369 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5370 sizeof(mirror::HeapReference<mirror::Object>));
5371 }
5372 }
5373 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5374 }
5375
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005376 return true;
5377}
5378
Vladimir Marko76649e82014-11-10 18:32:59 +00005379// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005380void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005381 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005382 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005383 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005384 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005385 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005386 // Compute reference offsets unless our superclass overflowed.
5387 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5388 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005389 if (num_reference_fields != 0u) {
5390 // All of the fields that contain object references are guaranteed be grouped in memory
5391 // starting at an appropriately aligned address after super class object data.
5392 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5393 sizeof(mirror::HeapReference<mirror::Object>));
5394 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005395 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005396 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005397 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005398 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005399 reference_offsets |= (0xffffffffu << start_bit) &
5400 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005401 }
5402 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005403 }
5404 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005405 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005406}
5407
Mathieu Chartier590fee92013-09-13 13:46:47 -07005408mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005409 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005410 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005411 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005412 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005413 return resolved;
5414 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005415 uint32_t utf16_length;
5416 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005417 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005418 dex_cache->SetResolvedString(string_idx, string);
5419 return string;
5420}
5421
Mathieu Chartier590fee92013-09-13 13:46:47 -07005422mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005423 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005424 StackHandleScope<2> hs(Thread::Current());
5425 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5426 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005427 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5428}
5429
5430mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005431 Handle<mirror::DexCache> dex_cache,
5432 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005433 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005434 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005435 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005436 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005437 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005438 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005439 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005440 // TODO: we used to throw here if resolved's class loader was not the
5441 // boot class loader. This was to permit different classes with the
5442 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005443 dex_cache->SetResolvedType(type_idx, resolved);
5444 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005445 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005446 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005447 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005448 StackHandleScope<1> hs(self);
5449 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005450 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005451 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005452 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005453 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005454 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005455 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005456 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005457 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005458 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005459 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005460 return resolved;
5461}
5462
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005463mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005464 Handle<mirror::DexCache> dex_cache,
5465 Handle<mirror::ClassLoader> class_loader,
5466 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005467 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005468 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005469 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005470 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005471 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005472 return resolved;
5473 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005474 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005475 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005476 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005477 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005478 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005479 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005480 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005481 // Scan using method_idx, this saves string compares but will only hit for matching dex
5482 // caches/files.
5483 switch (type) {
5484 case kDirect: // Fall-through.
5485 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005486 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005487 break;
5488 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005489 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005490 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005491 break;
5492 case kSuper: // Fall-through.
5493 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005494 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005495 break;
5496 default:
5497 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005498 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005499 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005500 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005501 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005502 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005503 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005504 switch (type) {
5505 case kDirect: // Fall-through.
5506 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005507 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005508 break;
5509 case kInterface:
5510 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005511 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005512 break;
5513 case kSuper: // Fall-through.
5514 case kVirtual:
5515 resolved = klass->FindVirtualMethod(name, signature);
5516 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005517 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005518 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005519 // If we found a method, check for incompatible class changes.
5520 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005521 // Be a good citizen and update the dex cache to speed subsequent calls.
5522 dex_cache->SetResolvedMethod(method_idx, resolved);
5523 return resolved;
5524 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005525 // If we had a method, it's an incompatible-class-change error.
5526 if (resolved != nullptr) {
5527 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5528 } else {
5529 // We failed to find the method which means either an access error, an incompatible class
5530 // change, or no such method. First try to find the method among direct and virtual methods.
5531 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5532 const Signature signature = dex_file.GetMethodSignature(method_id);
5533 switch (type) {
5534 case kDirect:
5535 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005536 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005537 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5538 // have had a resolved method before, which triggers the "true" branch above.
5539 break;
5540 case kInterface:
5541 case kVirtual:
5542 case kSuper:
5543 resolved = klass->FindDirectMethod(name, signature);
5544 break;
5545 }
5546
5547 // If we found something, check that it can be accessed by the referrer.
5548 if (resolved != nullptr && referrer.Get() != nullptr) {
5549 mirror::Class* methods_class = resolved->GetDeclaringClass();
5550 mirror::Class* referring_class = referrer->GetDeclaringClass();
5551 if (!referring_class->CanAccess(methods_class)) {
5552 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5553 resolved, type);
5554 return nullptr;
5555 } else if (!referring_class->CanAccessMember(methods_class,
5556 resolved->GetAccessFlags())) {
5557 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5558 return nullptr;
5559 }
5560 }
5561
5562 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5563 // methods and throw if we find the method there. If we find nothing, throw a
5564 // NoSuchMethodError.
5565 switch (type) {
5566 case kDirect:
5567 case kStatic:
5568 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005569 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005570 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005571 resolved = klass->FindInterfaceMethod(name, signature);
5572 if (resolved != nullptr) {
5573 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5574 } else {
5575 ThrowNoSuchMethodError(type, klass, name, signature);
5576 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005577 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005578 break;
5579 case kInterface:
5580 if (resolved != nullptr) {
5581 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005582 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005583 resolved = klass->FindVirtualMethod(name, signature);
5584 if (resolved != nullptr) {
5585 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5586 } else {
5587 ThrowNoSuchMethodError(type, klass, name, signature);
5588 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005589 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005590 break;
5591 case kSuper:
Andreas Gampedf733752014-08-25 20:55:01 -07005592 if (resolved != nullptr) {
5593 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5594 } else {
5595 ThrowNoSuchMethodError(type, klass, name, signature);
5596 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005597 break;
5598 case kVirtual:
5599 if (resolved != nullptr) {
5600 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5601 } else {
5602 resolved = klass->FindInterfaceMethod(name, signature);
5603 if (resolved != nullptr) {
5604 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5605 } else {
5606 ThrowNoSuchMethodError(type, klass, name, signature);
5607 }
5608 }
5609 break;
5610 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005611 }
5612 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005613 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005614 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005615}
5616
Mathieu Chartier590fee92013-09-13 13:46:47 -07005617mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005618 Handle<mirror::DexCache> dex_cache,
5619 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005620 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005621 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005622 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005623 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005624 return resolved;
5625 }
5626 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005627 Thread* const self = Thread::Current();
5628 StackHandleScope<1> hs(self);
5629 Handle<mirror::Class> klass(
5630 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005631 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005632 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005633 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005634 }
5635
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005636 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005637 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005638 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005639 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005640 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005641
Andreas Gampe58a5af82014-07-31 16:23:49 -07005642 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005643 const char* name = dex_file.GetFieldName(field_id);
5644 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5645 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005646 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005647 } else {
5648 resolved = klass->FindInstanceField(name, type);
5649 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005650 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005651 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005652 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005653 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005654 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005655 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005656 return resolved;
5657}
5658
Brian Carlstromea46f952013-07-30 01:26:50 -07005659mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005660 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005661 Handle<mirror::DexCache> dex_cache,
5662 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005663 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005664 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005665 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005666 return resolved;
5667 }
5668 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005669 Thread* self = Thread::Current();
5670 StackHandleScope<1> hs(self);
5671 Handle<mirror::Class> klass(
5672 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005673 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005674 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005675 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005676 }
5677
Ian Rogersdfb325e2013-10-30 01:00:44 -07005678 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5679 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005680 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005681 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005682 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005683 dex_cache->SetResolvedField(field_idx, resolved);
5684 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005685 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005686 }
5687 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005688}
5689
Brian Carlstromea46f952013-07-30 01:26:50 -07005690const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005691 uint32_t* length) {
5692 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5693 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005694 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005695 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005696 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005697}
5698
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005699void ClassLinker::DumpAllClasses(int flags) {
5700 if (dex_cache_image_class_lookup_required_) {
5701 MoveImageClassesToClassTable();
5702 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005703 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5704 // 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 -08005705 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005706 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005707 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005708 for (GcRoot<mirror::Class>& it : class_table_) {
5709 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005710 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005711 }
5712
5713 for (size_t i = 0; i < all_classes.size(); ++i) {
5714 all_classes[i]->DumpClass(std::cerr, flags);
5715 }
5716}
5717
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005718static OatFile::OatMethod CreateOatMethod(const void* code, const uint8_t* gc_map,
5719 bool is_portable) {
5720 CHECK_EQ(kUsePortableCompiler, is_portable);
5721 CHECK(code != nullptr);
5722 const uint8_t* base;
5723 uint32_t code_offset, gc_map_offset;
5724 if (gc_map == nullptr) {
5725 base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5726 base -= sizeof(void*); // Move backward so that code_offset != 0.
5727 code_offset = sizeof(void*);
5728 gc_map_offset = 0;
5729 } else {
5730 // TODO: 64bit support.
5731 base = nullptr; // Base of data in oat file, ie 0.
5732 code_offset = PointerToLowMemUInt32(code);
5733 gc_map_offset = PointerToLowMemUInt32(gc_map);
5734 }
5735 return OatFile::OatMethod(base, code_offset, gc_map_offset);
5736}
5737
5738bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5739 return (entry_point == GetPortableResolutionStub()) ||
5740 (portable_resolution_trampoline_ == entry_point);
5741}
5742
5743bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5744 return (entry_point == GetQuickResolutionStub()) ||
5745 (quick_resolution_trampoline_ == entry_point);
5746}
5747
5748bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5749 return (entry_point == GetPortableToInterpreterBridge());
5750 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5751}
5752
5753bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5754 return (entry_point == GetQuickToInterpreterBridge()) ||
5755 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5756}
5757
5758bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5759 return (entry_point == GetQuickGenericJniStub()) ||
5760 (quick_generic_jni_trampoline_ == entry_point);
5761}
5762
5763const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5764 return GetQuickGenericJniStub();
5765}
5766
5767void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5768 bool is_portable) const {
5769 OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr, is_portable);
5770 oat_method.LinkMethod(method);
5771 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5772 // Create bridges to transition between different kinds of compiled bridge.
5773 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5774 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5775 } else {
5776 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5777 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5778 method->SetIsPortableCompiled();
5779 }
5780}
5781
5782void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5783 if (!method->IsNative()) {
5784 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5785 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5786 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5787 } else {
5788 const void* quick_method_code = GetQuickGenericJniStub();
5789 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, nullptr, false);
5790 oat_method.LinkMethod(method);
5791 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5792 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5793 }
5794}
5795
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005796void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005797 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005798 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005799 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005800 MoveImageClassesToClassTable();
5801 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005802 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005803 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5804 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005805}
5806
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005807size_t ClassLinker::NumLoadedClasses() {
5808 if (dex_cache_image_class_lookup_required_) {
5809 MoveImageClassesToClassTable();
5810 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005811 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005812 // Only return non zygote classes since these are the ones which apps which care about.
5813 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005814}
5815
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005816pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005817 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005818}
5819
5820pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005821 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005822}
5823
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005824void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005825 DCHECK(!init_done_);
5826
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005827 DCHECK(klass != nullptr);
5828 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005829
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005830 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005831 DCHECK(class_roots != nullptr);
5832 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005833 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005834}
5835
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005836const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5837 static const char* class_roots_descriptors[] = {
5838 "Ljava/lang/Class;",
5839 "Ljava/lang/Object;",
5840 "[Ljava/lang/Class;",
5841 "[Ljava/lang/Object;",
5842 "Ljava/lang/String;",
5843 "Ljava/lang/DexCache;",
5844 "Ljava/lang/ref/Reference;",
5845 "Ljava/lang/reflect/ArtField;",
5846 "Ljava/lang/reflect/ArtMethod;",
5847 "Ljava/lang/reflect/Proxy;",
5848 "[Ljava/lang/String;",
5849 "[Ljava/lang/reflect/ArtField;",
5850 "[Ljava/lang/reflect/ArtMethod;",
5851 "Ljava/lang/ClassLoader;",
5852 "Ljava/lang/Throwable;",
5853 "Ljava/lang/ClassNotFoundException;",
5854 "Ljava/lang/StackTraceElement;",
5855 "Z",
5856 "B",
5857 "C",
5858 "D",
5859 "F",
5860 "I",
5861 "J",
5862 "S",
5863 "V",
5864 "[Z",
5865 "[B",
5866 "[C",
5867 "[D",
5868 "[F",
5869 "[I",
5870 "[J",
5871 "[S",
5872 "[Ljava/lang/StackTraceElement;",
5873 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005874 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5875 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005876
5877 const char* descriptor = class_roots_descriptors[class_root];
5878 CHECK(descriptor != nullptr);
5879 return descriptor;
5880}
5881
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005882std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5883 const {
5884 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005885 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005886}
5887
5888bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5889 const GcRoot<mirror::Class>& b) {
5890 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5891 return false;
5892 }
5893 std::string temp;
5894 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5895}
5896
5897std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5898 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005899 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005900}
5901
5902bool ClassLinker::ClassDescriptorHashEquals::operator()(
5903 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5904 if (a.Read()->GetClassLoader() != b.second) {
5905 return false;
5906 }
5907 return a.Read()->DescriptorEquals(b.first);
5908}
5909
5910bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5911 const char* descriptor) {
5912 return a.Read()->DescriptorEquals(descriptor);
5913}
5914
5915std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005916 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005917}
5918
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005919} // namespace art