blob: 4474f1be5b75120a60142933d1801815523bc94e [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogers700a4022014-05-19 16:49:03 -070020#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070021#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070022#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070023#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070024#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080027#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010028#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080030#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000032#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080033#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "dex_file-inl.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070035#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070036#include "gc/accounting/card_table-inl.h"
37#include "gc/accounting/heap_bitmap.h"
38#include "gc/heap.h"
39#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070040#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070041#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070042#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070043#include "leb128.h"
Ian Rogers1ff3c982014-08-12 02:30:58 -070044#include "method_helper-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080045#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070046#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070047#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070048#include "mirror/art_field-inl.h"
49#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "mirror/class.h"
51#include "mirror/class-inl.h"
52#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070053#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
57#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070058#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070060#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080061#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070062#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070063#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070064#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070065#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070066#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070067#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070068#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080069#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070070#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070071
72namespace art {
73
Ian Rogers00f7d0e2012-07-19 15:28:27 -070074static void ThrowNoClassDefFoundError(const char* fmt, ...)
75 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070076 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070077static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070078 va_list args;
79 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080080 Thread* self = Thread::Current();
81 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
82 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080083 va_end(args);
84}
85
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080086static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070087 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070088 // The class failed to initialize on a previous attempt, so we want to throw
89 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
90 // failed in verification, in which case v2 5.4.1 says we need to re-throw
91 // the previous error.
Ian Rogers7b078e82014-09-10 14:44:24 -070092 Runtime* runtime = Runtime::Current();
93 bool is_compiler = runtime->IsCompiler();
94 if (!is_compiler) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070095 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
96 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070097
Elliott Hughes5c599942012-06-13 16:45:05 -070098 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -080099 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700100 if (is_compiler) {
101 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
102 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
103 self->SetException(ThrowLocation(), pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700104 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700105 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
106 if (c->GetVerifyErrorClass() != NULL) {
107 // TODO: change the verifier to store an _instance_, with a useful detail message?
108 std::string temp;
109 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
110 PrettyDescriptor(c).c_str());
111 } else {
112 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
113 PrettyDescriptor(c).c_str());
114 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700115 }
116}
117
Ian Rogers62d6c772013-02-27 08:32:07 -0800118static void WrapExceptionInInitializer() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700119 Thread* self = Thread::Current();
120 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700121
122 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
123 CHECK(cause.get() != NULL);
124
125 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700126 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
127 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700128
Elliott Hughesa4f94742012-05-29 16:28:38 -0700129 // We only wrap non-Error exceptions; an Error can just be used as-is.
130 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800131 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
132 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;", NULL);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700133 }
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700134}
135
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800136static size_t Hash(const char* s) {
137 // This is the java.lang.String hashcode for convenience, not interoperability.
138 size_t hash = 0;
139 for (; *s != '\0'; ++s) {
140 hash = hash * 31 + *s;
141 }
142 return hash;
143}
144
Fred Shih381e4ca2014-08-25 17:24:27 -0700145// Gap between two fields in object layout.
146struct FieldGap {
147 uint32_t start_offset; // The offset from the start of the object.
148 uint32_t size; // The gap size of 1, 2, or 4 bytes.
149};
150struct FieldGapsComparator {
151 explicit FieldGapsComparator() {
152 }
153 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
154 NO_THREAD_SAFETY_ANALYSIS {
155 // Sort by gap size, largest first.
156 return lhs.size > rhs.size;
157 }
158};
159typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
160
161// Adds largest aligned gaps to queue of gaps.
162void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
163 DCHECK(gaps != nullptr);
164
165 uint32_t current_offset = gap_start;
166 while (current_offset != gap_end) {
167 size_t remaining = gap_end - current_offset;
168 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
169 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
170 current_offset += sizeof(uint32_t);
171 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
172 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
173 current_offset += sizeof(uint16_t);
174 } else {
175 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
176 current_offset += sizeof(uint8_t);
177 }
178 DCHECK_LE(current_offset, gap_end) << "Overran gap";
179 }
180}
181// Shuffle fields forward, making use of gaps whenever possible.
182template<int n>
183static void ShuffleForward(const size_t num_fields, size_t* current_field_idx,
184 MemberOffset* field_offset,
185 mirror::ObjectArray<mirror::ArtField>* fields,
186 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
187 FieldGaps* gaps)
188 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
189 DCHECK(current_field_idx != nullptr);
190 DCHECK(grouped_and_sorted_fields != nullptr);
191 DCHECK(fields != nullptr || (num_fields == 0 && grouped_and_sorted_fields->empty()));
192 DCHECK(gaps != nullptr);
193 DCHECK(field_offset != nullptr);
194
195 DCHECK(IsPowerOfTwo(n));
196 while (!grouped_and_sorted_fields->empty()) {
197 mirror::ArtField* field = grouped_and_sorted_fields->front();
198 Primitive::Type type = field->GetTypeAsPrimitiveType();
199 if (Primitive::ComponentSize(type) < n) {
200 break;
201 }
202 if (!IsAligned<n>(field_offset->Uint32Value())) {
203 MemberOffset old_offset = *field_offset;
204 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
205 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
206 }
207 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
208 grouped_and_sorted_fields->pop_front();
209 fields->Set<false>(*current_field_idx, field);
210 if (!gaps->empty() && gaps->top().size >= n) {
211 FieldGap gap = gaps->top();
212 gaps->pop();
213 DCHECK(IsAligned<n>(gap.start_offset));
214 field->SetOffset(MemberOffset(gap.start_offset));
215 if (gap.size > n) {
216 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
217 }
218 } else {
219 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
220 field->SetOffset(*field_offset);
221 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
222 }
223 ++(*current_field_idx);
224 }
225}
226
Elliott Hughes418d20f2011-09-22 14:00:39 -0700227const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700228 "Ljava/lang/Class;",
229 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700230 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700231 "[Ljava/lang/Object;",
232 "Ljava/lang/String;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700233 "Ljava/lang/DexCache;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700234 "Ljava/lang/ref/Reference;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700235 "Ljava/lang/reflect/ArtField;",
236 "Ljava/lang/reflect/ArtMethod;",
Ian Rogers466bb252011-10-14 03:29:56 -0700237 "Ljava/lang/reflect/Proxy;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700238 "[Ljava/lang/String;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700239 "[Ljava/lang/reflect/ArtField;",
240 "[Ljava/lang/reflect/ArtMethod;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700241 "Ljava/lang/ClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800242 "Ljava/lang/Throwable;",
jeffhao8cd6dda2012-02-22 10:15:34 -0800243 "Ljava/lang/ClassNotFoundException;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700244 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700245 "Z",
246 "B",
247 "C",
248 "D",
249 "F",
250 "I",
251 "J",
252 "S",
253 "V",
254 "[Z",
255 "[B",
256 "[C",
257 "[D",
258 "[F",
259 "[I",
260 "[J",
261 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700262 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700263};
264
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800265ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700266 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700267 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700268 dex_cache_image_class_lookup_required_(false),
269 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800270 class_roots_(nullptr),
271 array_iftable_(nullptr),
272 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700273 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800274 log_new_dex_caches_roots_(false),
275 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700276 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800277 portable_resolution_trampoline_(nullptr),
278 quick_resolution_trampoline_(nullptr),
279 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800280 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100281 quick_generic_jni_trampoline_(nullptr),
282 quick_to_interpreter_bridge_trampoline_(nullptr) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700283 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Ian Rogers98379392014-02-24 16:53:16 -0800284 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700285}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700286
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700287// To set a value for generic JNI. May be necessary in compiler tests.
288extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*);
Alex Light64ad14d2014-08-19 14:23:13 -0700289extern "C" void art_quick_resolution_trampoline(mirror::ArtMethod*);
290extern "C" void art_quick_imt_conflict_trampoline(mirror::ArtMethod*);
291extern "C" void art_quick_to_interpreter_bridge(mirror::ArtMethod*);
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700292
Alex Light64ad14d2014-08-19 14:23:13 -0700293void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800294 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700295 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700296
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700297 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700298
Elliott Hughes30646832011-10-13 16:59:46 -0700299 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700300 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700301 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700302 // 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 -0800303 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700304 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
305 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700306 heap->AllocNonMovableObject<true>(self, nullptr,
307 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700308 VoidFunctor()))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700309 CHECK(java_lang_Class.Get() != NULL);
310 mirror::Class::SetClassClass(java_lang_Class.Get());
311 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700312 if (kUseBakerOrBrooksReadBarrier) {
313 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800314 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700315 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800316 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800317 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700318
Elliott Hughes418d20f2011-09-22 14:00:39 -0700319 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700320 Handle<mirror::Class> class_array_class(hs.NewHandle(
321 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700322 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700323
Ian Rogers23435d02012-09-24 11:23:12 -0700324 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700325 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
326 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700327 CHECK(java_lang_Object.Get() != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700328 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700329 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700330 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700331
Ian Rogers23435d02012-09-24 11:23:12 -0700332 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700333 Handle<mirror::Class> object_array_class(hs.NewHandle(
334 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700335 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700336
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700337 // Setup the char (primitive) class to be used for char[].
338 Handle<mirror::Class> char_class(hs.NewHandle(
339 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700340
Ian Rogers23435d02012-09-24 11:23:12 -0700341 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700342 Handle<mirror::Class> char_array_class(hs.NewHandle(
343 AllocClass(self, java_lang_Class.Get(),
344 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700345 char_array_class->SetComponentType(char_class.Get());
346 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700347
Ian Rogers23435d02012-09-24 11:23:12 -0700348 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700349 Handle<mirror::Class> java_lang_String(hs.NewHandle(
350 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700351 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700352 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700353 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400354
Fred Shih4ee7a662014-07-11 09:59:27 -0700355 // Setup Reference.
356 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
357 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
358 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
359 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
360 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
361
Ian Rogers23435d02012-09-24 11:23:12 -0700362 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700363 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
364 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
365 kClassRootsMax));
366 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700367 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
368 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
369 SetClassRoot(kClassArrayClass, class_array_class.Get());
370 SetClassRoot(kObjectArrayClass, object_array_class.Get());
371 SetClassRoot(kCharArrayClass, char_array_class.Get());
372 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700373 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374
375 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700376 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
377 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
378 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
379 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
380 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
381 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
382 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
383 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384
Ian Rogers23435d02012-09-24 11:23:12 -0700385 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700386 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700387
Ian Rogers23435d02012-09-24 11:23:12 -0700388 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700389 Handle<mirror::Class> int_array_class(hs.NewHandle(
390 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700391 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700392 mirror::IntArray::SetArrayClass(int_array_class.Get());
393 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700394
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700395 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700396
Ian Rogers52813c92012-10-11 11:50:38 -0700397 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700398 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
399 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700400 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700401 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700402 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403
Brian Carlstromf3632832014-05-20 15:36:53 -0700404 // Constructor, Field, Method, and AbstractMethod are necessary so
405 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700406 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
407 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700408 CHECK(java_lang_reflect_ArtField.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700409 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700410 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700411 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700412 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700414 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
415 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700416 CHECK(java_lang_reflect_ArtMethod.Get() != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700417 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700418 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700419 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700420
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700421 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700422
423 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700424 Handle<mirror::Class> object_array_string(hs.NewHandle(
425 AllocClass(self, java_lang_Class.Get(),
426 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700427 object_array_string->SetComponentType(java_lang_String.Get());
428 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700429
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700430 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
431 AllocClass(self, java_lang_Class.Get(),
432 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700433 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
434 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700435
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700436 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
437 AllocClass(self, java_lang_Class.Get(),
438 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700439 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
440 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700441
Ian Rogers23435d02012-09-24 11:23:12 -0700442 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
443 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
444 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700445 CHECK_NE(0U, boot_class_path.size());
446 for (size_t i = 0; i != boot_class_path.size(); ++i) {
447 const DexFile* dex_file = boot_class_path[i];
448 CHECK(dex_file != NULL);
Ian Rogers7b078e82014-09-10 14:44:24 -0700449 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700450 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700451
452 // now we can use FindSystemClass
453
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700454 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700455 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
456 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700457
Jeff Hao88474b42013-10-23 16:24:40 -0700458 // Create runtime resolution and imt conflict methods. Also setup the default imt.
459 Runtime* runtime = Runtime::Current();
460 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
461 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
462 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
463
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700464 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
465 // we do not need friend classes or a publicly exposed setter.
466 quick_generic_jni_trampoline_ = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
Alex Light64ad14d2014-08-19 14:23:13 -0700467 if (!runtime->IsCompiler()) {
468 // We need to set up the generic trampolines since we don't have an image.
469 quick_resolution_trampoline_ = reinterpret_cast<void*>(art_quick_resolution_trampoline);
470 quick_imt_conflict_trampoline_ = reinterpret_cast<void*>(art_quick_imt_conflict_trampoline);
471 quick_to_interpreter_bridge_trampoline_ = reinterpret_cast<void*>(art_quick_to_interpreter_bridge);
472 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700473
Mathieu Chartier66f19252012-09-18 08:57:04 -0700474 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700475 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800476 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700477 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700478 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700479 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800480 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700481 std::ostringstream os1, os2;
482 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
483 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
484 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
485 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700486 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800487 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700488 CHECK_EQ(java_lang_String.Get(), String_class);
489 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700490 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700491
Ian Rogers23435d02012-09-24 11:23:12 -0700492 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800493 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800494 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700495
Ian Rogers98379392014-02-24 16:53:16 -0800496 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800497 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700498
Ian Rogers98379392014-02-24 16:53:16 -0800499 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700500 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700501
Ian Rogers98379392014-02-24 16:53:16 -0800502 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800503 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700504
Ian Rogers98379392014-02-24 16:53:16 -0800505 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700506 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700507
Ian Rogers98379392014-02-24 16:53:16 -0800508 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800509 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700510
Ian Rogers98379392014-02-24 16:53:16 -0800511 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800512 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700513
Ian Rogers98379392014-02-24 16:53:16 -0800514 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800515 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700516
Ian Rogers98379392014-02-24 16:53:16 -0800517 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700518 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700519
Ian Rogers98379392014-02-24 16:53:16 -0800520 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700521 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700522
Ian Rogers23435d02012-09-24 11:23:12 -0700523 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800524 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700525 CHECK(java_lang_Cloneable != NULL);
Ian Rogers98379392014-02-24 16:53:16 -0800526 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700527 CHECK(java_io_Serializable != NULL);
Ian Rogers23435d02012-09-24 11:23:12 -0700528 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
529 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700530 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700531 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700532 array_iftable->SetInterface(0, java_lang_Cloneable);
533 array_iftable->SetInterface(1, java_io_Serializable);
534 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700535
Ian Rogers23435d02012-09-24 11:23:12 -0700536 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700537 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
538 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
539 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
540 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700541 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700542 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800543 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700544 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700545
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700546 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800547 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700548 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700549
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700550 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800551 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700552 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700553
Brian Carlstromf3632832014-05-20 15:36:53 -0700554 mirror::Class* String_array_class =
555 FindSystemClass(self, class_roots_descriptors_[kJavaLangStringArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700556 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700557
Brian Carlstromea46f952013-07-30 01:26:50 -0700558 mirror::Class* Art_method_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800559 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700560 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700561
Brian Carlstromea46f952013-07-30 01:26:50 -0700562 mirror::Class* Art_field_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800563 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700564 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700565
Ian Rogers23435d02012-09-24 11:23:12 -0700566 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700567
Ian Rogers23435d02012-09-24 11:23:12 -0700568 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800569 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700570 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
571
Brian Carlstrom1f870082011-08-23 16:02:11 -0700572 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700573 // finish initializing Reference class
574 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
575 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
576 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
577 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
578 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700579 mirror::Class* java_lang_ref_FinalizerReference =
580 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700581 java_lang_ref_FinalizerReference->SetAccessFlags(
582 java_lang_ref_FinalizerReference->GetAccessFlags() |
583 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700584 mirror::Class* java_lang_ref_PhantomReference =
585 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700586 java_lang_ref_PhantomReference->SetAccessFlags(
587 java_lang_ref_PhantomReference->GetAccessFlags() |
588 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700589 mirror::Class* java_lang_ref_SoftReference =
590 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700591 java_lang_ref_SoftReference->SetAccessFlags(
592 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700593 mirror::Class* java_lang_ref_WeakReference =
594 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700595 java_lang_ref_WeakReference->SetAccessFlags(
596 java_lang_ref_WeakReference->GetAccessFlags() |
597 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700598
Ian Rogers23435d02012-09-24 11:23:12 -0700599 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800600 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700601 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700602 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
603
jeffhao8cd6dda2012-02-22 10:15:34 -0800604 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700605 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800606 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800607 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700608 SetClassRoot(kJavaLangClassNotFoundException,
609 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800610 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700611 SetClassRoot(kJavaLangStackTraceElementArrayClass,
612 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800613 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700614
Ian Rogers98379392014-02-24 16:53:16 -0800615 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700616
Brian Carlstroma004aa92012-02-08 18:05:09 -0800617 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700618}
619
Ian Rogers98379392014-02-24 16:53:16 -0800620void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800621 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700622
623 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700624 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700625 // as the types of the field can't be resolved prior to the runtime being
626 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800627 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700628 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800629 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800630
Brian Carlstromea46f952013-07-30 01:26:50 -0700631 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700632 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
633 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700634
Brian Carlstromea46f952013-07-30 01:26:50 -0700635 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700636 CHECK_STREQ(queue->GetName(), "queue");
637 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700638
Brian Carlstromea46f952013-07-30 01:26:50 -0700639 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700640 CHECK_STREQ(queueNext->GetName(), "queueNext");
641 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700642
Brian Carlstromea46f952013-07-30 01:26:50 -0700643 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700644 CHECK_STREQ(referent->GetName(), "referent");
645 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700646
Brian Carlstromea46f952013-07-30 01:26:50 -0700647 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700648 CHECK_STREQ(zombie->GetName(), "zombie");
649 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700650
Brian Carlstroma663ea52011-08-19 23:33:41 -0700651 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700652 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700653 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800654 mirror::Class* klass = GetClassRoot(class_root);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700655 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700656 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700657 // note SetClassRoot does additional validation.
658 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700659 }
660
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700661 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700662
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700663 // disable the slow paths in FindClass and CreatePrimitiveClass now
664 // that Object, Class, and Object[] are setup
665 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700666
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800667 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700668}
669
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700670void ClassLinker::RunRootClinits() {
671 Thread* self = Thread::Current();
672 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800673 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700674 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700675 StackHandleScope<1> hs(self);
676 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700677 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700678 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700679 }
680 }
681}
682
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700683bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800684 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000685 const char* oat_cache_filename,
686 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700687 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700688 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800689
Ian Rogers1d54e732013-05-02 21:10:01 -0700690 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800691 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700692 if (heap->GetImageSpace() == nullptr) {
693 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
694 // out of space anyway it might not matter.
695 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
696 "without an image.", dex_filename);
697 return false;
698 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700699 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800700
Brian Carlstrom6449c622014-02-10 23:48:36 -0800701 std::string dex_file_option("--dex-file=");
702 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800703
Brian Carlstrom6449c622014-02-10 23:48:36 -0800704 std::string oat_fd_option("--oat-fd=");
705 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800706
Brian Carlstrom6449c622014-02-10 23:48:36 -0800707 std::string oat_location_option("--oat-location=");
708 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800709
Brian Carlstrom6449c622014-02-10 23:48:36 -0800710 std::vector<std::string> argv;
711 argv.push_back(dex2oat);
712 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800713 argv.push_back("-classpath");
714 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800715 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800716
Ian Rogers8afeb852014-04-02 14:55:49 -0700717 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800718
Jeff Hao4a200f52014-04-01 14:58:49 -0700719 if (!Runtime::Current()->IsVerificationEnabled()) {
720 argv.push_back("--compiler-filter=verify-none");
721 }
722
Alex Light6e183f22014-07-18 14:57:04 -0700723 if (Runtime::Current()->MustRelocateIfPossible()) {
724 argv.push_back("--runtime-arg");
725 argv.push_back("-Xrelocate");
726 } else {
727 argv.push_back("--runtime-arg");
728 argv.push_back("-Xnorelocate");
729 }
730
Brian Carlstrom6449c622014-02-10 23:48:36 -0800731 if (!kIsTargetBuild) {
732 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700733 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700734
Brian Carlstrom6449c622014-02-10 23:48:36 -0800735 argv.push_back(boot_image_option);
736 argv.push_back(dex_file_option);
737 argv.push_back(oat_fd_option);
738 argv.push_back(oat_location_option);
739 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800740 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800741 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700742 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800743
744 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700745}
746
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700747const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700748 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800749 if (kIsDebugBuild) {
750 for (size_t i = 0; i < oat_files_.size(); ++i) {
751 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700752 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800753 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700754 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
755 oat_files_.push_back(oat_file);
756 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800757}
758
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700759OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
760 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700761 OatFile* oat_file = space->ReleaseOatFile();
762 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700763 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700764 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700765}
766
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100767const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800768 const char* dex_location = dex_file.GetLocation().c_str();
769 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100770 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800771}
772
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100773const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
774 const char* dex_location,
775 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700776 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100777 for (const OatFile* oat_file : oat_files_) {
778 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700779
780 if (oat_location != nullptr) {
781 if (oat_file->GetLocation() != oat_location) {
782 continue;
783 }
784 }
785
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700786 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800787 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700788 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100789 if (oat_dex_file != nullptr) {
790 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800791 }
792 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100793 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800794}
795
Calin Juravle621962a2014-09-02 15:53:55 +0100796
797// Loads all multi dex files from the given oat file returning true on success.
798//
799// Parameters:
800// oat_file - the oat file to load from
801// dex_location - the dex location used to generate the oat file
802// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
803// generated - whether or not the oat_file existed before or was just (re)generated
804// error_msgs - any error messages will be appended here
805// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
806static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
807 const char* dex_location,
808 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700809 bool generated,
810 std::vector<std::string>* error_msgs,
811 std::vector<const DexFile*>* dex_files) {
812 if (oat_file == nullptr) {
813 return false;
814 }
815
816 size_t old_size = dex_files->size(); // To rollback on error.
817
818 bool success = true;
819 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100820 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700821 const char* next_name = next_name_str.c_str();
822
Calin Juravle621962a2014-09-02 15:53:55 +0100823 uint32_t next_location_checksum;
824 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700825 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100826 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
827 // When i=0 the multidex name should be the same as the location name. We already have the
828 // checksum it so we don't need to recompute it.
829 if (dex_location_checksum == nullptr) {
830 next_location_checksum_pointer = nullptr;
831 } else {
832 next_location_checksum = *dex_location_checksum;
833 }
834 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700835 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100836 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700837 }
838
839 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
840
841 if (oat_dex_file == nullptr) {
842 if (i == 0 && generated) {
843 std::string error_msg;
844 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100845 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700846 oat_file->GetLocation().c_str());
847 error_msgs->push_back(error_msg);
848 }
849 break; // Not found, done.
850 }
851
852 // Checksum test. Test must succeed when generated.
853 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100854 if (next_location_checksum_pointer != nullptr) {
855 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700856 }
857
858 if (success) {
859 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
860 if (dex_file == nullptr) {
861 success = false;
862 error_msgs->push_back(error_msg);
863 } else {
864 dex_files->push_back(dex_file);
865 }
866 }
867
868 // When we generated the file, we expect success, or something is terribly wrong.
869 CHECK_EQ(false, generated && !success)
870 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100871 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700872 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
873 }
874
875 if (dex_files->size() == old_size) {
876 success = false; // We did not even find classes.dex
877 }
878
879 if (success) {
880 return true;
881 } else {
882 // Free all the dex files we have loaded.
883 auto it = dex_files->begin() + old_size;
884 auto it_end = dex_files->end();
885 for (; it != it_end; it++) {
886 delete *it;
887 }
888 dex_files->erase(dex_files->begin() + old_size, it_end);
889
890 return false;
891 }
892}
893
894// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
895// complicates the loading process, as we should not use an iterative loading process, because that
896// would register the oat file and dex files that come before the broken one. Instead, check all
897// multidex ahead of time.
898bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
899 std::vector<std::string>* error_msgs,
900 std::vector<const DexFile*>* dex_files) {
901 // 1) Check whether we have an open oat file.
902 // This requires a dex checksum, use the "primary" one.
903 uint32_t dex_location_checksum;
904 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
905 bool have_checksum = true;
906 std::string checksum_error_msg;
907 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100908 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700909 dex_location_checksum_pointer = nullptr;
910 have_checksum = false;
911 }
912
913 bool needs_registering = false;
914
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100915 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
916 dex_location_checksum_pointer);
917 std::unique_ptr<const OatFile> open_oat_file(
918 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700919
920 // 2) If we do not have an open one, maybe there's one on disk already.
921
922 // In case the oat file is not open, we play a locking game here so
923 // that if two different processes race to load and register or generate
924 // (or worse, one tries to open a partial generated file) we will be okay.
925 // This is actually common with apps that use DexClassLoader to work
926 // around the dex method reference limit and that have a background
927 // service running in a separate process.
928 ScopedFlock scoped_flock;
929
930 if (open_oat_file.get() == nullptr) {
931 if (oat_location != nullptr) {
932 // Can only do this if we have a checksum, else error.
933 if (!have_checksum) {
934 error_msgs->push_back(checksum_error_msg);
935 return false;
936 }
937
938 std::string error_msg;
939
940 // We are loading or creating one in the future. Time to set up the file lock.
941 if (!scoped_flock.Init(oat_location, &error_msg)) {
942 error_msgs->push_back(error_msg);
943 return false;
944 }
945
Alex Lighta59dd802014-07-02 16:28:08 -0700946 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700947 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
948 oat_location, &error_msg));
949
950 if (open_oat_file.get() == nullptr) {
951 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
952 dex_location, oat_location, error_msg.c_str());
953 VLOG(class_linker) << compound_msg;
954 error_msgs->push_back(compound_msg);
955 }
956 } else {
957 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100958 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700959 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
960 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100961 kRuntimeISA, error_msgs,
962 &obsolete_file_cleanup_failed));
963 // There's no point in going forward and eventually try to regenerate the
964 // file if we couldn't remove the obsolete one. Mostly likely we will fail
965 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100966 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
967 if (obsolete_file_cleanup_failed) {
968 return false;
969 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700970 }
971 needs_registering = true;
972 }
973
974 // 3) If we have an oat file, check all contained multidex files for our dex_location.
975 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100976 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
977 dex_location_checksum_pointer,
978 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700979 if (success) {
980 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
981 if (needs_registering) {
982 // We opened the oat file, so we must register it.
983 RegisterOatFile(oat_file);
984 }
Alex Light9dcc4572014-08-14 14:16:26 -0700985 // If the file isn't executable we failed patchoat but did manage to get the dex files.
986 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700987 } else {
988 if (needs_registering) {
989 // We opened it, delete it.
990 open_oat_file.reset();
991 } else {
992 open_oat_file.release(); // Do not delete open oat files.
993 }
994 }
995
996 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
997
998 // Need a checksum, fail else.
999 if (!have_checksum) {
1000 error_msgs->push_back(checksum_error_msg);
1001 return false;
1002 }
1003
1004 // Look in cache location if no oat_location is given.
1005 std::string cache_location;
1006 if (oat_location == nullptr) {
1007 // Use the dalvik cache.
1008 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
1009 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
1010 oat_location = cache_location.c_str();
1011 }
1012
Alex Light64ad14d2014-08-19 14:23:13 -07001013 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -07001014 // Definitely need to lock now.
1015 if (!scoped_flock.HasFile()) {
1016 std::string error_msg;
1017 if (!scoped_flock.Init(oat_location, &error_msg)) {
1018 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -07001019 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -07001020 }
1021 }
1022
Alex Light64ad14d2014-08-19 14:23:13 -07001023 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001024 // Create the oat file.
1025 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1026 oat_location, error_msgs));
1027 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001028
1029 // Failed, bail.
1030 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001031 std::string error_msg;
1032 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1033 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1034 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001035 return false;
1036 }
1037
1038 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001039 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1040 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001041 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001042 if (success) {
1043 RegisterOatFile(open_oat_file.release());
1044 return true;
1045 } else {
1046 return false;
1047 }
1048}
1049
1050const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1051 uint32_t dex_location_checksum,
1052 const char* oat_location,
1053 std::string* error_msg) {
Ian Rogers700a4022014-05-19 16:49:03 -07001054 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001055 !Runtime::Current()->IsCompiler(),
1056 error_msg));
1057 if (oat_file.get() == nullptr) {
1058 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1059 error_msg->c_str());
1060 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001061 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001062 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001063 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1064 if (image_space != nullptr) {
1065 const ImageHeader& image_header = image_space->GetImageHeader();
1066 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1067 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1068 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1069 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1070 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1071 actual_image_oat_checksum);
1072 return nullptr;
1073 }
1074
1075 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1076 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1077 if (expected_image_oat_offset != actual_image_oat_offset) {
1078 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1079 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1080 actual_image_oat_offset);
1081 return nullptr;
1082 }
1083 int32_t expected_patch_delta = image_header.GetPatchDelta();
1084 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1085 if (expected_patch_delta != actual_patch_delta) {
1086 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1087 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1088 return nullptr;
1089 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001090 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001091
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001092 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1093 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001094 if (oat_dex_file == nullptr) {
1095 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1096 dex_location);
1097 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001098 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001099 uint32_t expected_dex_checksum = dex_location_checksum;
1100 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1101 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001102 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1103 "found 0x%x", oat_location, expected_dex_checksum,
1104 actual_dex_checksum);
1105 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001106 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001107 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1108 if (dex_file.get() != nullptr) {
1109 return oat_file.release();
1110 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001111 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001112 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001113}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001114
Andreas Gampe833a4852014-05-21 18:46:59 -07001115const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1116 int fd, const char* oat_location,
1117 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001118 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001119 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001120 std::string error_msg;
1121 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001122 CHECK(!error_msg.empty());
1123 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001124 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001125 }
Ian Rogers700a4022014-05-19 16:49:03 -07001126 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001127 !Runtime::Current()->IsCompiler(),
1128 &error_msg));
1129 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001130 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1131 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001132 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001133 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001134 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001135
1136 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001137}
1138
Alex Light6e183f22014-07-18 14:57:04 -07001139bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1140 const InstructionSet instruction_set) {
1141 Runtime* runtime = Runtime::Current();
1142 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001143 if (image_space == nullptr) {
1144 return false;
1145 }
Alex Light6e183f22014-07-18 14:57:04 -07001146 uint32_t image_oat_checksum = 0;
1147 if (instruction_set == kRuntimeISA) {
1148 const ImageHeader& image_header = image_space->GetImageHeader();
1149 image_oat_checksum = image_header.GetOatChecksum();
1150 } else {
1151 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1152 image_space->GetImageLocation().c_str(), instruction_set));
1153 image_oat_checksum = image_header->GetOatChecksum();
1154 }
1155 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1156}
1157
1158bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1159 const InstructionSet instruction_set,
1160 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001161 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001162 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001163 if (image_space == nullptr) {
1164 *error_msg = "No image space for verification against";
1165 return false;
1166 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001167
1168 // If the requested instruction set is the same as the current runtime,
1169 // we can use the checksums directly. If it isn't, we'll have to read the
1170 // image header from the image for the right instruction set.
1171 uint32_t image_oat_checksum = 0;
1172 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001173 int32_t image_patch_delta = 0;
1174 if (instruction_set == Runtime::Current()->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001175 const ImageHeader& image_header = image_space->GetImageHeader();
1176 image_oat_checksum = image_header.GetOatChecksum();
1177 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001178 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001179 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001180 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001181 image_space->GetImageLocation().c_str(), instruction_set));
1182 image_oat_checksum = image_header->GetOatChecksum();
1183 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001184 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001185 }
1186 const OatHeader& oat_header = oat_file->GetOatHeader();
Alex Light6e183f22014-07-18 14:57:04 -07001187 bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1188 && (oat_header.GetImagePatchDelta() == image_patch_delta)
1189 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1190 if (!ret) {
1191 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1192 oat_file->GetLocation().c_str(),
1193 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1194 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1195 oat_file->GetOatHeader().GetImagePatchDelta(),
1196 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1197 }
1198 return ret;
1199}
1200
1201bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1202 const char* dex_location,
1203 uint32_t dex_location_checksum,
1204 const InstructionSet instruction_set,
1205 std::string* error_msg) {
1206 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1207 return false;
1208 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001209
Brian Carlstromf3632832014-05-20 15:36:53 -07001210 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1211 &dex_location_checksum);
Brian Carlstromafe25512012-06-27 17:02:58 -07001212 if (oat_dex_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001213 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1214 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001215 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1216 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001217 oat_file->GetLocation().c_str(),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001218 oat_dex_file->GetDexFileLocation().c_str(),
1219 oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001220 }
1221 return false;
1222 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001223
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001224 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001225 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001226}
1227
Alex Lighta59dd802014-07-02 16:28:08 -07001228bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1229 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001230 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001231 std::string* error_msg) {
1232 CHECK(oat_file != nullptr);
1233 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001234 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001235 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001236 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1237 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1238 // directory.
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001239 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, NULL);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001240 if (oat_dex_file == nullptr) {
1241 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001242 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001243 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001244 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001245 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001246 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001247 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001248 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001249 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001250 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001251 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001252 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001253 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001254 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001255 }
Alex Lighta59dd802014-07-02 16:28:08 -07001256 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001257}
1258
Andreas Gampe833a4852014-05-21 18:46:59 -07001259const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001260 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001261 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001262 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001263 std::vector<std::string>* error_msgs,
1264 bool* obsolete_file_cleanup_failed) {
1265 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001266 bool already_opened = false;
1267 std::string dex_location_str(dex_location);
1268 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1269 &already_opened,
1270 obsolete_file_cleanup_failed,
1271 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001272 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001273 if (oat_file.get() == nullptr) {
1274 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1275 dex_location));
1276 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001277 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001278 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1279 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001280 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1281 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001282 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001283 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001284 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001285 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001286 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1287 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1288 "dex location '%s'. Image checksum incorrect.",
1289 oat_file->GetLocation().c_str(), dex_location));
1290 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001291 } else {
1292 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001293 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001294}
1295
Brian Carlstromae826982011-11-09 01:33:42 -08001296const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001297 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001298 for (size_t i = 0; i < oat_files_.size(); i++) {
1299 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001300 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001301 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001302 return oat_file;
1303 }
1304 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001305 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001306}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001307
Alex Lighta59dd802014-07-02 16:28:08 -07001308const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1309 InstructionSet isa,
1310 bool *already_opened,
1311 bool *obsolete_file_cleanup_failed,
1312 std::vector<std::string>* error_msgs) {
1313 // Find out if we've already opened the file
1314 const OatFile* ret = nullptr;
1315 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1316 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1317 if (ret != nullptr) {
1318 *already_opened = true;
1319 return ret;
1320 }
1321
1322 std::string dalvik_cache;
1323 bool have_android_data = false;
1324 bool have_dalvik_cache = false;
1325 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
1326 &have_android_data, &have_dalvik_cache);
1327 std::string cache_filename;
1328 if (have_dalvik_cache) {
1329 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1330 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1331 if (ret != nullptr) {
1332 *already_opened = true;
1333 return ret;
1334 }
1335 } else {
1336 // If we need to relocate we should just place odex back where it started.
1337 cache_filename = odex_filename;
1338 }
1339
1340 ret = nullptr;
1341
1342 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1343 //
1344 // Now we do the following:
1345 // 1) Try and open the odex version
1346 // 2) If present, checksum-verified & relocated correctly return it
1347 // 3) Close the odex version to free up its address space.
1348 // 4) Try and open the cache version
1349 // 5) If present, checksum-verified & relocated correctly return it
1350 // 6) Close the cache version to free up its address space.
1351 // 7) If we should relocate:
1352 // a) If we have opened and checksum-verified the odex version relocate it to
1353 // 'cache_filename' and return it
1354 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1355 // it. This should not happen often (I think only the run-test's will hit this case).
1356 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1357 // this point.
1358 // 9) Return nullptr
1359
1360 *already_opened = false;
1361 const Runtime* runtime = Runtime::Current();
1362 CHECK(runtime != nullptr);
1363 bool executable = !runtime->IsCompiler();
1364
1365 std::string odex_error_msg;
1366 bool should_patch_system = false;
1367 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001368 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001369 {
1370 // There is a high probability that these both these oat files map similar/the same address
1371 // spaces so we must scope them like this so they each gets its turn.
1372 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, NULL,
1373 executable, &odex_error_msg));
1374 if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1375 &odex_checksum_verified,
1376 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001377 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001378 } else {
1379 if (odex_checksum_verified) {
1380 // We can just relocate
1381 should_patch_system = true;
1382 odex_error_msg = "Image Patches are incorrect";
1383 }
1384 if (odex_oat_file.get() != nullptr) {
1385 have_system_odex = true;
1386 }
Alex Lighta59dd802014-07-02 16:28:08 -07001387 }
1388 }
1389
Alex Lighta59dd802014-07-02 16:28:08 -07001390 std::string cache_error_msg;
1391 bool should_patch_cache = false;
1392 bool cache_checksum_verified = false;
1393 if (have_dalvik_cache) {
1394 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, NULL,
1395 executable, &cache_error_msg));
1396 if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1397 &cache_checksum_verified,
1398 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001399 return cache_oat_file.release();
1400 } else if (cache_checksum_verified) {
1401 // We can just relocate
1402 should_patch_cache = true;
1403 cache_error_msg = "Image Patches are incorrect";
1404 }
1405 } else if (have_android_data) {
1406 // dalvik_cache does not exist but android data does. This means we should be able to create
1407 // it, so we should try.
1408 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1409 }
1410
1411 ret = nullptr;
1412 std::string error_msg;
1413 if (runtime->CanRelocate()) {
1414 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001415 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1416 if (space != nullptr) {
1417 const std::string& image_location = space->GetImageLocation();
1418 if (odex_checksum_verified && should_patch_system) {
1419 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1420 } else if (cache_checksum_verified && should_patch_cache) {
1421 CHECK(have_dalvik_cache);
1422 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1423 }
Alex Light84d76052014-08-22 17:49:35 -07001424 } else if (have_system_odex) {
1425 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001426 }
1427 }
1428 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1429 // implicitly: were able to fine where the cached version is but we were unable to use it,
1430 // either as a destination for relocation or to open a file. We should delete it if it is
1431 // there.
1432 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1433 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1434 "searching for dex file %s: %s",
1435 cache_filename.c_str(), dex_location.c_str(),
1436 strerror(errno));
1437 error_msgs->push_back(rm_error_msg);
1438 VLOG(class_linker) << rm_error_msg;
1439 // Let the caller know that we couldn't remove the obsolete file.
1440 // This is a good indication that further writes may fail as well.
1441 *obsolete_file_cleanup_failed = true;
1442 }
1443 }
1444 if (ret == nullptr) {
1445 VLOG(class_linker) << error_msg;
1446 error_msgs->push_back(error_msg);
1447 std::string relocation_msg;
1448 if (runtime->CanRelocate()) {
1449 relocation_msg = StringPrintf(" and relocation failed");
1450 }
1451 if (have_dalvik_cache && cache_checksum_verified) {
1452 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1453 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1454 cache_filename.c_str(), cache_error_msg.c_str(),
1455 relocation_msg.c_str());
1456 } else {
1457 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1458 "dalvik_cache availible)%s.", odex_filename.c_str(),
1459 odex_error_msg.c_str(), relocation_msg.c_str());
1460 }
1461 VLOG(class_linker) << error_msg;
1462 error_msgs->push_back(error_msg);
1463 }
1464 return ret;
1465}
1466
Alex Light9dcc4572014-08-14 14:16:26 -07001467const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1468 InstructionSet isa,
1469 std::string* error_msg) {
1470 // We open it non-executable
1471 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, NULL, false, error_msg));
1472 if (output.get() == nullptr) {
1473 return nullptr;
1474 }
Alex Light84d76052014-08-22 17:49:35 -07001475 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1476 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001477 return output.release();
1478 } else {
1479 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1480 oat_path.c_str());
1481 return nullptr;
1482 }
1483}
1484
Alex Lighta59dd802014-07-02 16:28:08 -07001485const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1486 const std::string& output_oat,
1487 const std::string& image_location,
1488 InstructionSet isa,
1489 std::string* error_msg) {
Alex Light64ad14d2014-08-19 14:23:13 -07001490 if (!Runtime::Current()->GetHeap()->HasImageSpace()) {
1491 // We don't have an image space so there is no point in trying to patchoat.
1492 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1493 << "running without an image. Attempting to use oat file for interpretation.";
1494 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1495 }
Alex Light9dcc4572014-08-14 14:16:26 -07001496 if (!Runtime::Current()->IsDex2OatEnabled()) {
1497 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1498 // input_oat but make sure we only do interpretation on it's dex files.
1499 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1500 << "disabled. Attempting to use oat file for interpretation";
1501 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1502 }
Alex Lighta59dd802014-07-02 16:28:08 -07001503 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
1504 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1505
1506 std::string isa_arg("--instruction-set=");
1507 isa_arg += GetInstructionSetString(isa);
1508 std::string input_oat_filename_arg("--input-oat-file=");
1509 input_oat_filename_arg += input_oat;
1510 std::string output_oat_filename_arg("--output-oat-file=");
1511 output_oat_filename_arg += output_oat;
1512 std::string patched_image_arg("--patched-image-location=");
1513 patched_image_arg += image_location;
1514
1515 std::vector<std::string> argv;
1516 argv.push_back(patchoat);
1517 argv.push_back(isa_arg);
1518 argv.push_back(input_oat_filename_arg);
1519 argv.push_back(output_oat_filename_arg);
1520 argv.push_back(patched_image_arg);
1521
1522 std::string command_line(Join(argv, ' '));
1523 LOG(INFO) << "Relocate Oat File: " << command_line;
1524 bool success = Exec(argv, error_msg);
1525 if (success) {
1526 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, NULL,
1527 !Runtime::Current()->IsCompiler(), error_msg));
1528 bool checksum_verified = false;
1529 if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1530 return output.release();
1531 } else if (output.get() != nullptr) {
1532 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1533 "but output file '%s' failed verifcation: %s",
1534 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1535 } else {
1536 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1537 "but was unable to open output file '%s': %s",
1538 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1539 }
Alex Light9dcc4572014-08-14 14:16:26 -07001540 } else if (!Runtime::Current()->IsCompiler()) {
1541 // patchoat failed which means we probably don't have enough room to place the output oat file,
1542 // instead of failing we should just run the interpreter from the dex files in the input oat.
1543 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1544 << "for interpretation. patchoat failure was: " << *error_msg;
1545 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001546 } else {
1547 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1548 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1549 error_msg->c_str());
1550 }
1551 return nullptr;
1552}
1553
1554int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1555 Runtime* runtime = Runtime::Current();
1556 int32_t real_patch_delta;
1557 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001558 CHECK(image_space != nullptr);
Alex Lighta59dd802014-07-02 16:28:08 -07001559 if (isa == Runtime::Current()->GetInstructionSet()) {
1560 const ImageHeader& image_header = image_space->GetImageHeader();
1561 real_patch_delta = image_header.GetPatchDelta();
1562 } else {
1563 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1564 image_space->GetImageLocation().c_str(), isa));
1565 real_patch_delta = image_header->GetPatchDelta();
1566 }
1567 const OatHeader& oat_header = oat_file->GetOatHeader();
1568 return real_patch_delta - oat_header.GetImagePatchDelta();
1569}
1570
1571bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1572 bool* checksum_verified,
1573 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001574 Runtime* runtime = Runtime::Current();
Alex Lighta59dd802014-07-02 16:28:08 -07001575 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001576 if (image_space == nullptr) {
1577 *error_msg = "No image space present";
1578 return false;
1579 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001580 uint32_t real_image_checksum;
1581 void* real_image_oat_offset;
1582 int32_t real_patch_delta;
1583 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001584 const ImageHeader& image_header = image_space->GetImageHeader();
1585 real_image_checksum = image_header.GetOatChecksum();
1586 real_image_oat_offset = image_header.GetOatDataBegin();
1587 real_patch_delta = image_header.GetPatchDelta();
1588 } else {
1589 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1590 image_space->GetImageLocation().c_str(), isa));
1591 real_image_checksum = image_header->GetOatChecksum();
1592 real_image_oat_offset = image_header->GetOatDataBegin();
1593 real_patch_delta = image_header->GetPatchDelta();
1594 }
1595
1596 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001597 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001598
1599 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1600 *checksum_verified = oat_image_checksum == real_image_checksum;
1601 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001602 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1603 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001604 }
1605
1606 void* oat_image_oat_offset =
1607 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1608 bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1609 if (!offset_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001610 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1611 real_image_oat_offset, oat_image_oat_offset);
Alex Lighta59dd802014-07-02 16:28:08 -07001612 }
1613
1614 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1615 bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1616 if (!patch_delta_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001617 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, received 0x%x)",
1618 real_patch_delta, oat_patch_delta);
Alex Lighta59dd802014-07-02 16:28:08 -07001619 }
1620
1621 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001622 if (!ret) {
1623 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001624 }
1625 return ret;
1626}
1627
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001628const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1629 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001630 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001631 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001632 return oat_file;
1633 }
1634
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001635 oat_file = OatFile::Open(oat_location, oat_location, NULL, !Runtime::Current()->IsCompiler(),
1636 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001637 if (oat_file == NULL) {
Brian Carlstroma004aa92012-02-08 18:05:09 -08001638 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001639 }
1640 return oat_file;
1641}
1642
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001643static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001644 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001645 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1646
Ian Rogers848871b2013-08-05 10:56:33 -07001647 DCHECK(obj != NULL);
1648 DCHECK(class_linker != NULL);
1649
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001650 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001651 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001652 if (!method->IsNative()) {
1653 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1654 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001655 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1656 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001657 }
1658 }
1659 }
1660}
1661
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001662void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001663 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001664 CHECK(!init_done_);
1665
Mathieu Chartier590fee92013-09-13 13:46:47 -07001666 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001667 gc::Heap* heap = Runtime::Current()->GetHeap();
1668 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001669 dex_cache_image_class_lookup_required_ = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001670 CHECK(space != NULL);
1671 OatFile& oat_file = GetImageOatFile(space);
1672 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1673 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001674 const char* image_file_location = oat_file.GetOatHeader().
1675 GetStoreValueByKey(OatHeader::kImageLocationKey);
1676 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001677 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1678 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001679 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1680 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001681 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001682 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001683 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1684 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1685 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001686
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001687 StackHandleScope<1> hs(self);
1688 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1689 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1690 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001691 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001692
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001693 // Special case of setting up the String class early so that we can test arbitrary objects
1694 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001695 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001696
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001697 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001698 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001699 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001700 StackHandleScope<1> hs(self);
1701 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001702 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001703 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1704 nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001705 CHECK(oat_dex_file != NULL) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001706 std::string error_msg;
1707 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001708 if (dex_file == NULL) {
1709 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001710 << " from within oat file " << oat_file.GetLocation()
1711 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001712 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001713
1714 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1715
1716 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001717 }
1718
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001719 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1720 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001721 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001722
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001723 // Set entry point to interpreter if in InterpretOnly mode.
1724 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001725 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001726 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001727 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001728
1729 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001730 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001731 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001732
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001733 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001734 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1735 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001736 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001737 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001738 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001739 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1740 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1741 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1742 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1743 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1744 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1745 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1746 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1747 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1748 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001749
Ian Rogers98379392014-02-24 16:53:16 -08001750 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001751
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001752 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001753}
1754
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001755void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1756 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1757 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001758 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1759 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001760 }
1761 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1762 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001763 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1764 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1765 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1766 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001767 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1768 // corresponding object. This is slow, but luckily for us, this may only happen with a
1769 // concurrent moving GC.
1770 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1771 it != end && it->first == pair.first; ++it) {
1772 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001773 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1774 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001775 }
1776 }
1777 }
1778 }
1779 }
1780 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1781 new_class_roots_.clear();
1782 }
1783 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1784 log_new_class_table_roots_ = true;
1785 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1786 log_new_class_table_roots_ = false;
1787 }
1788 // We deliberately ignore the class roots in the image since we
1789 // handle image roots by using the MS/CMS rescanning of dirty cards.
1790}
1791
Brian Carlstroma663ea52011-08-19 23:33:41 -07001792// Keep in sync with InitCallback. Anything we visit, we need to
1793// reinit references to when reinitializing a ClassLinker from a
1794// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001795void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001796 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001797 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001798 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001799 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001800 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001801 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1802 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001803 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001804 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1805 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001806 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001807 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001808 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001809 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1810 new_dex_cache_roots_.clear();
1811 }
1812 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1813 log_new_dex_caches_roots_ = true;
1814 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1815 log_new_dex_caches_roots_ = false;
1816 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001817 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001818 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001819 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1820 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001821 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001822 if (!find_array_class_cache_[i].IsNull()) {
1823 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001824 }
1825 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001826}
1827
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001828void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1829 if (dex_cache_image_class_lookup_required_) {
1830 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001831 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001832 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001833 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001834 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1835 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001836 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001837 return;
1838 }
1839 }
1840}
1841
Ian Rogersdbf3be02014-08-29 15:40:08 -07001842static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001843 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001844 classes->insert(c);
1845 return true;
1846}
1847
Ian Rogersdbf3be02014-08-29 15:40:08 -07001848struct GetClassesVisitorArrayArg {
1849 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1850 int32_t index;
1851 bool success;
1852};
1853
1854static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1855 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1856 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1857 if (arg->index < (*arg->classes)->GetLength()) {
1858 (*arg->classes)->Set(arg->index, c);
1859 arg->index++;
1860 return true;
1861 } else {
1862 arg->success = false;
1863 return false;
1864 }
1865}
1866
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001867void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001868 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1869 // is avoiding duplicates.
1870 if (!kMovingClasses) {
1871 std::set<mirror::Class*> classes;
1872 VisitClasses(GetClassesVisitorSet, &classes);
1873 for (mirror::Class* klass : classes) {
1874 if (!visitor(klass, arg)) {
1875 return;
1876 }
1877 }
1878 } else {
1879 Thread* self = Thread::Current();
1880 StackHandleScope<1> hs(self);
1881 Handle<mirror::ObjectArray<mirror::Class>> classes =
1882 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1883 GetClassesVisitorArrayArg local_arg;
1884 local_arg.classes = &classes;
1885 local_arg.success = false;
1886 // We size the array assuming classes won't be added to the class table during the visit.
1887 // If this assumption fails we iterate again.
1888 while (!local_arg.success) {
1889 size_t class_table_size;
1890 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001891 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001892 class_table_size = class_table_.size();
1893 }
1894 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1895 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1896 classes.Assign(
1897 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1898 CHECK(classes.Get() != nullptr); // OOME.
1899 local_arg.index = 0;
1900 local_arg.success = true;
1901 VisitClasses(GetClassesVisitorArray, &local_arg);
1902 }
1903 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1904 // If the class table shrank during creation of the clases array we expect null elements. If
1905 // the class table grew then the loop repeats. If classes are created after the loop has
1906 // finished then we don't visit.
1907 mirror::Class* klass = classes->Get(i);
1908 if (klass != nullptr && !visitor(klass, arg)) {
1909 return;
1910 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001911 }
1912 }
1913}
1914
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001915ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001916 mirror::Class::ResetClass();
1917 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001918 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001919 mirror::ArtField::ResetClass();
1920 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001921 mirror::BooleanArray::ResetArrayClass();
1922 mirror::ByteArray::ResetArrayClass();
1923 mirror::CharArray::ResetArrayClass();
1924 mirror::DoubleArray::ResetArrayClass();
1925 mirror::FloatArray::ResetArrayClass();
1926 mirror::IntArray::ResetArrayClass();
1927 mirror::LongArray::ResetArrayClass();
1928 mirror::ShortArray::ResetArrayClass();
1929 mirror::Throwable::ResetClass();
1930 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001931 STLDeleteElements(&boot_class_path_);
1932 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001933}
1934
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001935mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001936 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001937 StackHandleScope<16> hs(self);
1938 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1939 Handle<mirror::DexCache> dex_cache(
1940 hs.NewHandle(down_cast<mirror::DexCache*>(
1941 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1942 VoidFunctor()))));
1943 if (dex_cache.Get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001944 return NULL;
1945 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001946 Handle<mirror::String>
1947 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
1948 if (location.Get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001949 return NULL;
1950 }
Ian Rogers700a4022014-05-19 16:49:03 -07001951 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001952 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
1953 if (strings.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001954 return NULL;
1955 }
Ian Rogers700a4022014-05-19 16:49:03 -07001956 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001957 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
1958 if (types.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001959 return NULL;
1960 }
Ian Rogers700a4022014-05-19 16:49:03 -07001961 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001962 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
1963 if (methods.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001964 return NULL;
1965 }
Ian Rogers700a4022014-05-19 16:49:03 -07001966 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001967 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
1968 if (fields.Get() == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001969 return NULL;
1970 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001971 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1972 fields.Get());
1973 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001974}
1975
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001976mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001977 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001978 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001979 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001980 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001981 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001982 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1983 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001984 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001985 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001986 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001987 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001988 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001989}
1990
Ian Rogers6fac4472014-02-25 17:01:10 -08001991mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001992 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001993}
1994
Brian Carlstromea46f952013-07-30 01:26:50 -07001995mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001996 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001997 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001998}
1999
Brian Carlstromea46f952013-07-30 01:26:50 -07002000mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002001 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002002 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002003}
2004
Mathieu Chartier590fee92013-09-13 13:46:47 -07002005mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2006 Thread* self, size_t length) {
2007 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2008 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002009}
2010
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002011mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2012 mirror::Class* klass) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002013 DCHECK(klass != NULL);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002014
2015 // For temporary classes we must wait for them to be retired.
2016 if (init_done_ && klass->IsTemp()) {
2017 CHECK(!klass->IsResolved());
2018 if (klass->IsErroneous()) {
2019 ThrowEarlierClassFailure(klass);
2020 return nullptr;
2021 }
2022 StackHandleScope<1> hs(self);
2023 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2024 ObjectLock<mirror::Class> lock(self, h_class);
2025 // Loop and wait for the resolving thread to retire this class.
2026 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2027 lock.WaitIgnoringInterrupts();
2028 }
2029 if (h_class->IsErroneous()) {
2030 ThrowEarlierClassFailure(h_class.Get());
2031 return nullptr;
2032 }
2033 CHECK(h_class->IsRetired());
2034 // Get the updated class from class table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002035 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002036 }
2037
Brian Carlstromaded5f72011-10-07 17:15:04 -07002038 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002039 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002040 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002041 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2042 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002043 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002044 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2045 ThrowClassCircularityError(h_class.Get());
2046 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002047 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002048 }
2049 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002050 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002051 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002052 }
2053 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002054
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002055 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002056 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002057 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002058 }
2059 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002060 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002061 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002062 return klass;
2063}
2064
Ian Rogers68b56852014-08-29 20:19:11 -07002065typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2066
2067// Search a collection of DexFiles for a descriptor
2068ClassPathEntry FindInClassPath(const char* descriptor,
2069 const std::vector<const DexFile*>& class_path) {
2070 for (size_t i = 0; i != class_path.size(); ++i) {
2071 const DexFile* dex_file = class_path[i];
2072 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
2073 if (dex_class_def != NULL) {
2074 return ClassPathEntry(dex_file, dex_class_def);
2075 }
2076 }
2077 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
2078 return ClassPathEntry(reinterpret_cast<const DexFile*>(NULL),
2079 reinterpret_cast<const DexFile::ClassDef*>(NULL));
2080}
2081
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002082mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2083 Thread* self, const char* descriptor,
2084 ConstHandle<mirror::ClassLoader> class_loader) {
2085 if (class_loader->GetClass() !=
2086 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2087 class_loader->GetParent()->GetClass() !=
2088 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2089 return nullptr;
2090 }
2091 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2092 // Check if this would be found in the parent boot class loader.
2093 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002094 mirror::Class* klass = LookupClass(self, descriptor, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002095 if (klass != nullptr) {
2096 return EnsureResolved(self, descriptor, klass);
2097 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002098 klass = DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002099 *pair.second);
2100 if (klass != nullptr) {
2101 return klass;
2102 }
2103 CHECK(self->IsExceptionPending()) << descriptor;
2104 self->ClearException();
2105 } else {
2106 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2107 StackHandleScope<3> hs(self);
2108 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2109 // We need to get the DexPathList and loop through it.
2110 Handle<mirror::ArtField> cookie_field =
2111 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2112 Handle<mirror::ArtField> dex_file_field =
2113 hs.NewHandle(
2114 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList$Element_dexFile));
2115 mirror::Object* dex_path_list =
2116 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2117 GetObject(class_loader.Get());
2118 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2119 cookie_field.Get() != nullptr) {
2120 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2121 mirror::Object* dex_elements_obj =
2122 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2123 GetObject(dex_path_list);
2124 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2125 // at the mCookie which is a DexFile vector.
2126 if (dex_elements_obj != nullptr) {
2127 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2128 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2129 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2130 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2131 if (element == nullptr) {
2132 // Should never happen, fall back to java code to throw a NPE.
2133 break;
2134 }
2135 mirror::Object* dex_file = dex_file_field->GetObject(element);
2136 if (dex_file != nullptr) {
2137 const uint64_t cookie = cookie_field->GetLong(dex_file);
2138 auto* dex_files =
2139 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2140 if (dex_files == nullptr) {
2141 // This should never happen so log a warning.
2142 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2143 break;
2144 }
2145 for (const DexFile* dex_file : *dex_files) {
2146 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
2147 if (dex_class_def != nullptr) {
2148 RegisterDexFile(*dex_file);
2149 mirror::Class* klass =
Ian Rogers7b078e82014-09-10 14:44:24 -07002150 DefineClass(self, descriptor, class_loader, *dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002151 if (klass == nullptr) {
2152 CHECK(self->IsExceptionPending()) << descriptor;
2153 self->ClearException();
2154 return nullptr;
2155 }
2156 return klass;
2157 }
2158 }
2159 }
2160 }
2161 }
2162 }
2163 }
2164 return nullptr;
2165}
2166
Ian Rogers98379392014-02-24 16:53:16 -08002167mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002168 ConstHandle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002169 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002170 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002171 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002172 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002173 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2174 // for primitive classes that aren't backed by dex files.
2175 return FindPrimitiveClass(descriptor[0]);
2176 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002177 // Find the class in the loaded classes table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002178 mirror::Class* klass = LookupClass(self, descriptor, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002179 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002180 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002181 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002182 // Class is not yet loaded.
2183 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08002184 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002185 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002186 // The boot class loader, search the boot class path.
Ian Rogers68b56852014-08-29 20:19:11 -07002187 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2188 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002189 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2190 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002191 } else {
2192 // The boot class loader is searched ahead of the application class loader, failures are
2193 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2194 // trigger the chaining with a proper stack trace.
2195 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2196 self->SetException(ThrowLocation(), pre_allocated);
2197 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002198 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002199 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002200 // First try with the bootstrap class loader.
2201 if (class_loader.Get() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002202 klass = LookupClass(self, descriptor, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002203 if (klass != nullptr) {
2204 return EnsureResolved(self, descriptor, klass);
2205 }
2206 }
Ian Rogers63557452014-06-04 16:57:15 -07002207 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2208 // a NoClassDefFoundError being allocated.
Ian Rogers68b56852014-08-29 20:19:11 -07002209 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2210 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002211 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2212 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002213 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002214 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002215 const std::vector<const DexFile*>* class_path;
2216 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002217 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002218 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002219 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002220 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2221 }
Ian Rogers68b56852014-08-29 20:19:11 -07002222 pair = FindInClassPath(descriptor, *class_path);
2223 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002224 return DefineClass(self, descriptor, class_loader, *pair.first, *pair.second);
2225 } else {
2226 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2227 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2228 self->SetException(ThrowLocation(), pre_allocated);
2229 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002230 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002231 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002232 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002233 mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, class_loader);
2234 if (klass != nullptr) {
2235 return klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002236 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002237 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002238 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002239 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002240 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002241 {
2242 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002243 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2244 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002245 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002246 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002247 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002248 }
Ian Rogers68b56852014-08-29 20:19:11 -07002249 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002250 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2251 WellKnownClasses::java_lang_ClassLoader_loadClass,
2252 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002253 }
Ian Rogers98379392014-02-24 16:53:16 -08002254 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002255 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002256 return nullptr;
2257 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002258 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002259 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002260 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002261 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002262 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002263 // success, return mirror::Class*
2264 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002265 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002266 }
2267
Elliott Hughes82914b62012-04-09 15:56:29 -07002268 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002269 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002270}
2271
Ian Rogers7b078e82014-09-10 14:44:24 -07002272mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002273 ConstHandle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002274 const DexFile& dex_file,
2275 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002276 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002277 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002278 bool should_allocate = false;
2279
Brian Carlstromaded5f72011-10-07 17:15:04 -07002280 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002281 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002282 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002283 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002284 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002285 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002286 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002287 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002288 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002289 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2290 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002291 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002292 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002293 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002294 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002295 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002296 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002297 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002298 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002299 }
2300 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002301 should_allocate = true;
2302 }
2303
2304 if (should_allocate) {
2305 // Allocate a class with the status of not ready.
2306 // Interface object should get the right size here. Regular class will
2307 // figure out the right size later and be replaced with one of the right
2308 // size when the class becomes resolved.
2309 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002310 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002311 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002312 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002313 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002314 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002315 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002316 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002317 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002318 if (self->IsExceptionPending()) {
2319 // An exception occured during load, set status to erroneous while holding klass' lock in case
2320 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002321 if (!klass->IsErroneous()) {
2322 klass->SetStatus(mirror::Class::kStatusError, self);
2323 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002324 return nullptr;
2325 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002326 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002327
Mathieu Chartier590fee92013-09-13 13:46:47 -07002328 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002329 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07002330 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002331 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2332 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002333 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002334 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002335
Brian Carlstromaded5f72011-10-07 17:15:04 -07002336 // Finish loading (if necessary) by finding parents
2337 CHECK(!klass->IsLoaded());
2338 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2339 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002340 if (!klass->IsErroneous()) {
2341 klass->SetStatus(mirror::Class::kStatusError, self);
2342 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002343 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002344 }
2345 CHECK(klass->IsLoaded());
2346 // Link the class (if necessary)
2347 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002348 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002349 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002350
2351 mirror::Class* new_class = nullptr;
2352 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002353 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002354 if (!klass->IsErroneous()) {
2355 klass->SetStatus(mirror::Class::kStatusError, self);
2356 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002357 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002358 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002359 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002360 CHECK(new_class != nullptr) << descriptor;
2361 CHECK(new_class->IsResolved()) << descriptor;
2362
2363 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002364
2365 /*
2366 * We send CLASS_PREPARE events to the debugger from here. The
2367 * definition of "preparation" is creating the static fields for a
2368 * class and initializing them to the standard default values, but not
2369 * executing any code (that comes later, during "initialization").
2370 *
2371 * We did the static preparation in LinkClass.
2372 *
2373 * The class has been prepared and resolved but possibly not yet verified
2374 * at this point.
2375 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002376 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002377
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002378 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002379}
2380
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002381uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2382 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002383 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002384 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002385 size_t num_8 = 0;
2386 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002387 size_t num_32 = 0;
2388 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002389 if (class_data != NULL) {
2390 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2391 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002392 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002393 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002394 switch (c) {
2395 case 'L':
2396 case '[':
2397 num_ref++;
2398 break;
2399 case 'J':
2400 case 'D':
2401 num_64++;
2402 break;
2403 case 'I':
2404 case 'F':
2405 num_32++;
2406 break;
2407 case 'S':
2408 case 'C':
2409 num_16++;
2410 break;
2411 case 'B':
2412 case 'Z':
2413 num_8++;
2414 break;
2415 default:
2416 LOG(FATAL) << "Unknown descriptor: " << c;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002417 }
2418 }
2419 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002420 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002421}
2422
Ian Rogers97b52f82014-08-14 11:34:07 -07002423OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2424 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002425 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002426 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2427 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002428 *found = false;
2429 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002430 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002431 *found = true;
2432 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002433}
2434
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002435static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2436 uint32_t method_idx) {
2437 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2438 const byte* class_data = dex_file.GetClassData(class_def);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002439 CHECK(class_data != NULL);
2440 ClassDataItemIterator it(dex_file, class_data);
2441 // Skip fields
2442 while (it.HasNextStaticField()) {
2443 it.Next();
2444 }
2445 while (it.HasNextInstanceField()) {
2446 it.Next();
2447 }
2448 // Process methods
2449 size_t class_def_method_index = 0;
2450 while (it.HasNextDirectMethod()) {
2451 if (it.GetMemberIndex() == method_idx) {
2452 return class_def_method_index;
2453 }
2454 class_def_method_index++;
2455 it.Next();
2456 }
2457 while (it.HasNextVirtualMethod()) {
2458 if (it.GetMemberIndex() == method_idx) {
2459 return class_def_method_index;
2460 }
2461 class_def_method_index++;
2462 it.Next();
2463 }
2464 DCHECK(!it.HasNext());
2465 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2466 return 0;
2467}
2468
Ian Rogers97b52f82014-08-14 11:34:07 -07002469const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002470 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002471 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002472 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002473 size_t oat_method_index;
2474 if (method->IsStatic() || method->IsDirect()) {
2475 // Simple case where the oat method index was stashed at load time.
2476 oat_method_index = method->GetMethodIndex();
2477 } else {
2478 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2479 // by search for its position in the declared virtual methods.
2480 oat_method_index = declaring_class->NumDirectMethods();
2481 size_t end = declaring_class->NumVirtualMethods();
2482 bool found = false;
2483 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002484 // Check method index instead of identity in case of duplicate method definitions.
2485 if (method->GetDexMethodIndex() ==
2486 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002487 found = true;
2488 break;
2489 }
Ian Rogersf320b632012-03-13 18:47:47 -07002490 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002491 }
2492 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2493 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002494 DCHECK_EQ(oat_method_index,
2495 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002496 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002497 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002498 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2499 declaring_class->GetDexClassDefIndex(),
2500 found);
2501 if (!found) {
2502 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002503 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002504 *found = true;
2505 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002506}
2507
2508// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002509const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002510 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002511 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002512 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002513 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002514 bool found;
2515 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002516 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002517 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002518 result = oat_method.GetQuickCode();
2519 }
2520
Ian Rogersef7d42f2014-01-06 12:55:46 -08002521 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002522 if (method->IsNative()) {
2523 // No code and native? Use generic trampoline.
2524 result = GetQuickGenericJniTrampoline();
2525 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002526 // No code? Do we expect portable code?
2527 result = GetQuickToPortableBridge();
2528 } else {
2529 // No code? You must mean to go into the interpreter.
2530 result = GetQuickToInterpreterBridge();
2531 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002532 }
2533 return result;
TDYa12785321912012-04-01 15:24:56 -07002534}
2535
Ian Rogersef7d42f2014-01-06 12:55:46 -08002536const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2537 bool* have_portable_code) {
2538 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2539 *have_portable_code = false;
2540 if (method->IsProxyMethod()) {
2541 return GetPortableProxyInvokeHandler();
2542 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002543 bool found;
2544 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002545 const void* result = nullptr;
2546 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002547 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002548 result = oat_method.GetPortableCode();
2549 quick_code = oat_method.GetQuickCode();
2550 }
2551
Ian Rogersef7d42f2014-01-06 12:55:46 -08002552 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002553 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002554 // No code? You must mean to go into the interpreter.
2555 result = GetPortableToInterpreterBridge();
2556 } else {
2557 // No code? But there's quick code, so use a bridge.
2558 result = GetPortableToQuickBridge();
2559 }
2560 } else {
2561 *have_portable_code = true;
2562 }
2563 return result;
2564}
2565
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002566const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2567 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2568 return nullptr;
2569 }
2570 bool found;
2571 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2572 return found ? oat_method.GetQuickCode() : nullptr;
2573}
2574
2575const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2576 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2577 return nullptr;
2578 }
2579 bool found;
2580 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2581 return found ? oat_method.GetPortableCode() : nullptr;
2582}
2583
Ian Rogersef7d42f2014-01-06 12:55:46 -08002584const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2585 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002586 bool found;
2587 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2588 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002589 return nullptr;
2590 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002591 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002592 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002593}
2594
2595const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2596 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002597 bool found;
2598 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2599 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002600 return nullptr;
2601 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002602 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002603 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002604}
2605
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002606// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002607static bool NeedsInterpreter(
2608 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2609 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002610 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002611 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002612 // May return true for native code, in the case of generic JNI
2613 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002614 return true;
2615 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002616#ifdef ART_SEA_IR_MODE
2617 ScopedObjectAccess soa(Thread::Current());
2618 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2619 LOG(INFO) << "Found " << PrettyMethod(method);
2620 return false;
2621 }
2622#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002623 // If interpreter mode is enabled, every method (except native and proxy) must
2624 // be run with interpreter.
2625 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2626 !method->IsNative() && !method->IsProxyMethod();
2627}
2628
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002629void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002630 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002631 if (klass->NumDirectMethods() == 0) {
2632 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002633 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002634 Runtime* runtime = Runtime::Current();
2635 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002636 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2637 return; // OAT file unavailable.
2638 }
Ian Rogers19846512012-02-24 11:42:47 -08002639 }
Alex Light64ad14d2014-08-19 14:23:13 -07002640
Mathieu Chartierf8322842014-05-16 10:59:25 -07002641 const DexFile& dex_file = klass->GetDexFile();
2642 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002643 CHECK(dex_class_def != nullptr);
2644 const byte* class_data = dex_file.GetClassData(*dex_class_def);
2645 // There should always be class data if there were direct methods.
2646 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002647 ClassDataItemIterator it(dex_file, class_data);
2648 // Skip fields
2649 while (it.HasNextStaticField()) {
2650 it.Next();
2651 }
2652 while (it.HasNextInstanceField()) {
2653 it.Next();
2654 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002655 bool has_oat_class;
2656 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2657 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002658 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002659 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002660 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002661 if (!method->IsStatic()) {
2662 // Only update static methods.
2663 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002664 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002665 const void* portable_code = nullptr;
2666 const void* quick_code = nullptr;
2667 if (has_oat_class) {
2668 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2669 portable_code = oat_method.GetPortableCode();
2670 quick_code = oat_method.GetQuickCode();
2671 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002672 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2673 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002674 if (enter_interpreter) {
2675 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002676 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002677 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2678 quick_code = GetQuickGenericJniTrampoline();
Ian Rogers1a570662014-03-12 01:02:21 -07002679 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002680 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002681 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002682 quick_code = GetQuickToInterpreterBridge();
2683 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002684 } else {
2685 if (portable_code == nullptr) {
2686 portable_code = GetPortableToQuickBridge();
2687 } else {
2688 have_portable_code = true;
2689 }
2690 if (quick_code == nullptr) {
2691 quick_code = GetQuickToPortableBridge();
2692 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002693 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002694 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2695 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002696 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002697 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002698}
2699
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002700void ClassLinker::LinkCode(ConstHandle<mirror::ArtMethod> method,
2701 const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002702 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002703 uint32_t method_index) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002704 if (Runtime::Current()->IsCompiler()) {
2705 // The following code only applies to a non-compiler runtime.
2706 return;
2707 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002708 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002709 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2710 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002711 if (oat_class != nullptr) {
2712 // Every kind of method should at least get an invoke stub from the oat_method.
2713 // non-abstract methods also get their code pointers.
2714 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2715 oat_method.LinkMethod(method.Get());
2716 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002717
Jeff Hao16743632013-05-08 10:59:04 -07002718 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002719 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002720 method->GetEntryPointFromQuickCompiledCode(),
2721 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002722 if (enter_interpreter && !method->IsNative()) {
Ian Rogers848871b2013-08-05 10:56:33 -07002723 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002724 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002725 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002726 }
2727
Brian Carlstrom92827a52011-10-10 15:50:01 -07002728 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002729 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2730 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002731 return;
2732 }
Ian Rogers19846512012-02-24 11:42:47 -08002733
Ian Rogersef7d42f2014-01-06 12:55:46 -08002734 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002735 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002736 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002737 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2738 // after initializing class (see ClassLinker::InitializeClass method).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002739 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline());
2740 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002741 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002742 if (!method->IsNative()) {
2743 // Set entry point from compiled code if there's no code or in interpreter only mode.
2744 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2745 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2746 } else {
2747 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline());
2748 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2749 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002750 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2751 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2752 have_portable_code = true;
2753 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2754 } else {
2755 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2756 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002757 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002758
Ian Rogers62d6c772013-02-27 08:32:07 -08002759 if (method->IsNative()) {
2760 // Unregistering restores the dlsym lookup stub.
2761 method->UnregisterNative(Thread::Current());
Andreas Gampe90546832014-03-12 18:07:19 -07002762
2763 if (enter_interpreter) {
2764 // We have a native method here without code. Then it should have either the GenericJni
2765 // trampoline as entrypoint (non-static), or the Resolution trampoline (static).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002766 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline()
Andreas Gampe9a6a99a2014-03-14 07:52:20 -07002767 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline());
Andreas Gampe90546832014-03-12 18:07:19 -07002768 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002769 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002770
Ian Rogers62d6c772013-02-27 08:32:07 -08002771 // Allow instrumentation its chance to hijack code.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002772 Runtime* runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002773 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002774 method->GetEntryPointFromQuickCompiledCode(),
2775 method->GetEntryPointFromPortableCompiledCode(),
2776 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002777}
2778
Fred Shih37f05ef2014-07-16 18:38:08 -07002779
Fred Shih37f05ef2014-07-16 18:38:08 -07002780
Ian Rogers7b078e82014-09-10 14:44:24 -07002781void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002782 const DexFile::ClassDef& dex_class_def,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002783 ConstHandle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002784 mirror::ClassLoader* class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002785 CHECK(klass.Get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002786 CHECK(klass->GetDexCache() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002787 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002788 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002789 CHECK(descriptor != NULL);
2790
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002791 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002792 if (kUseBakerOrBrooksReadBarrier) {
2793 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002794 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002795 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07002796 // Make sure that none of our runtime-only flags are set.
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002797 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002798 klass->SetAccessFlags(access_flags);
2799 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002800 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002801 klass->SetStatus(mirror::Class::kStatusIdx, NULL);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002802
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002803 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002804 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002805
Ian Rogers0571d352011-11-03 19:51:38 -07002806 const byte* class_data = dex_file.GetClassData(dex_class_def);
2807 if (class_data == NULL) {
2808 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002809 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002810
Ian Rogers97b52f82014-08-14 11:34:07 -07002811
2812 bool has_oat_class = false;
2813 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2814 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2815 &has_oat_class);
2816 if (has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002817 LoadClassMembers(self, dex_file, class_data, klass, class_loader, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002818 }
2819 }
2820 if (!has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002821 LoadClassMembers(self, dex_file, class_data, klass, class_loader, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002822 }
2823}
2824
Ian Rogers7b078e82014-09-10 14:44:24 -07002825void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002826 const byte* class_data,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002827 ConstHandle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002828 mirror::ClassLoader* class_loader,
2829 const OatFile::OatClass* oat_class) {
2830 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002831 ClassDataItemIterator it(dex_file, class_data);
2832 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002833 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
2834 if (UNLIKELY(statics == NULL)) {
2835 CHECK(self->IsExceptionPending()); // OOME.
2836 return;
2837 }
2838 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002839 }
2840 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002841 mirror::ObjectArray<mirror::ArtField>* fields =
2842 AllocArtFieldArray(self, it.NumInstanceFields());
2843 if (UNLIKELY(fields == NULL)) {
2844 CHECK(self->IsExceptionPending()); // OOME.
2845 return;
2846 }
2847 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002848 }
2849 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002850 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002851 StackHandleScope<1> hs(self);
2852 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
2853 if (UNLIKELY(sfield.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002854 CHECK(self->IsExceptionPending()); // OOME.
2855 return;
2856 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002857 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002858 LoadField(dex_file, it, klass, sfield);
2859 }
2860 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002861 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002862 StackHandleScope<1> hs(self);
2863 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
2864 if (UNLIKELY(ifield.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002865 CHECK(self->IsExceptionPending()); // OOME.
2866 return;
2867 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002868 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002869 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002870 }
2871
Ian Rogers0571d352011-11-03 19:51:38 -07002872 // Load methods.
2873 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002874 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002875 mirror::ObjectArray<mirror::ArtMethod>* directs =
2876 AllocArtMethodArray(self, it.NumDirectMethods());
2877 if (UNLIKELY(directs == NULL)) {
2878 CHECK(self->IsExceptionPending()); // OOME.
2879 return;
2880 }
2881 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002882 }
Ian Rogers0571d352011-11-03 19:51:38 -07002883 if (it.NumVirtualMethods() != 0) {
2884 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002885 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2886 AllocArtMethodArray(self, it.NumVirtualMethods());
2887 if (UNLIKELY(virtuals == NULL)) {
2888 CHECK(self->IsExceptionPending()); // OOME.
2889 return;
2890 }
2891 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002892 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002893 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002894 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2895 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002896 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002897 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002898 StackHandleScope<1> hs(self);
2899 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2900 if (UNLIKELY(method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002901 CHECK(self->IsExceptionPending()); // OOME.
2902 return;
2903 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002904 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002905 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002906 uint32_t it_method_index = it.GetMemberIndex();
2907 if (last_dex_method_index == it_method_index) {
2908 // duplicate case
2909 method->SetMethodIndex(last_class_def_method_index);
2910 } else {
2911 method->SetMethodIndex(class_def_method_index);
2912 last_dex_method_index = it_method_index;
2913 last_class_def_method_index = class_def_method_index;
2914 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002915 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002916 }
2917 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002918 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002919 StackHandleScope<1> hs(self);
2920 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2921 if (UNLIKELY(method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002922 CHECK(self->IsExceptionPending()); // OOME.
2923 return;
2924 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002925 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002926 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002927 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002928 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002929 }
2930 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002931}
2932
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002933void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002934 ConstHandle<mirror::Class> klass,
2935 ConstHandle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002936 uint32_t field_idx = it.GetMemberIndex();
2937 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002938 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002939 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002940}
2941
Brian Carlstromea46f952013-07-30 01:26:50 -07002942mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002943 const ClassDataItemIterator& it,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002944 ConstHandle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002945 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002946 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002947 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002948
Brian Carlstromea46f952013-07-30 01:26:50 -07002949 mirror::ArtMethod* dst = AllocArtMethod(self);
Ian Rogersa436fde2013-08-27 23:34:06 -07002950 if (UNLIKELY(dst == NULL)) {
2951 CHECK(self->IsExceptionPending()); // OOME.
2952 return NULL;
2953 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002954 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002955
Ian Rogers50b35e22012-10-04 10:09:15 -07002956 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002957 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002958 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002959 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002960
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002961 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002962 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002963 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002964
Ian Rogers241b5de2013-10-09 17:58:57 -07002965 uint32_t access_flags = it.GetMemberAccessFlags();
2966
Ian Rogersdfb325e2013-10-30 01:00:44 -07002967 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002968 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002969 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2970 // Void return type.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002971 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002972 klass->SetFinalizable();
2973 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002974 std::string temp;
2975 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002976 // The Enum class declares a "final" finalize() method to prevent subclasses from
2977 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2978 // subclasses, so we exclude it here.
2979 // We also want to avoid setting the flag on Object, where we know that finalize() is
2980 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002981 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2982 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002983 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002984 }
2985 }
2986 }
2987 } else if (method_name[0] == '<') {
2988 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002989 bool is_init = (strcmp("<init>", method_name) == 0);
2990 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002991 if (UNLIKELY(!is_init && !is_clinit)) {
2992 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2993 } else {
2994 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2995 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002996 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002997 access_flags |= kAccConstructor;
2998 }
2999 }
3000 }
3001 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003002
Ian Rogers50b35e22012-10-04 10:09:15 -07003003 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003004 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07003005}
3006
Ian Rogers7b078e82014-09-10 14:44:24 -07003007void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003008 StackHandleScope<1> hs(self);
3009 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
3010 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003011 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003012}
3013
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003014void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07003015 ConstHandle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003016 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003017 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003018 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003019}
3020
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003021bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003022 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07003023 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003024 mirror::DexCache* dex_cache = GetDexCache(i);
3025 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08003026 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003027 }
3028 }
3029 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003030}
3031
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003032bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003033 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003034 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003035}
3036
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003037void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07003038 ConstHandle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003039 dex_lock_.AssertExclusiveHeld(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003040 CHECK(dex_cache.Get() != NULL) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003041 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3042 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003043 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003044 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003045 if (log_new_dex_caches_roots_) {
3046 // TODO: This is not safe if we can remove dex caches.
3047 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3048 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003049}
3050
Brian Carlstromaded5f72011-10-07 17:15:04 -07003051void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003052 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003053 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003054 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003055 if (IsDexFileRegisteredLocked(dex_file)) {
3056 return;
3057 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003058 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003059 // Don't alloc while holding the lock, since allocation may need to
3060 // suspend all threads and another thread may need the dex_lock_ to
3061 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003062 StackHandleScope<1> hs(self);
3063 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
3064 CHECK(dex_cache.Get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003065 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003066 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003067 if (IsDexFileRegisteredLocked(dex_file)) {
3068 return;
3069 }
3070 RegisterDexFileLocked(dex_file, dex_cache);
3071 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003072}
3073
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003074void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07003075 ConstHandle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003076 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003077 RegisterDexFileLocked(dex_file, dex_cache);
3078}
3079
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003080mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003081 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003082 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003083 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003084 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003085 if (dex_cache->GetDexFile() == &dex_file) {
3086 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003087 }
3088 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003089 // Search matching by location name.
3090 std::string location(dex_file.GetLocation());
3091 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003092 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003093 if (dex_cache->GetDexFile()->GetLocation() == location) {
3094 return dex_cache;
3095 }
3096 }
3097 // Failure, dump diagnostic and abort.
3098 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003099 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003100 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3101 }
3102 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003103 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003104}
3105
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003106void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003107 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003108 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003109 mirror::DexCache* dex_cache = GetDexCache(i);
3110 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003111 }
3112}
3113
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003114mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003115 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Ian Rogersa436fde2013-08-27 23:34:06 -07003116 if (UNLIKELY(klass == NULL)) {
3117 return NULL;
3118 }
3119 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003120}
3121
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003122mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3123 Primitive::Type type) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003124 CHECK(primitive_class != NULL);
Ian Rogers1f539342012-10-03 21:09:42 -07003125 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003126 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003127 StackHandleScope<1> hs(self);
3128 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003129 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003130 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003131 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003132 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3133 const char* descriptor = Primitive::Descriptor(type);
3134 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Ian Rogersc8982582012-09-07 16:53:25 -07003135 CHECK(existing == NULL) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003136 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003137}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003138
Brian Carlstrombe977852011-07-19 14:54:54 -07003139// Create an array class (i.e. the class object for the array, not the
3140// array itself). "descriptor" looks like "[C" or "[[[[B" or
3141// "[Ljava/lang/String;".
3142//
3143// If "descriptor" refers to an array of primitives, look up the
3144// primitive type's internally-generated class object.
3145//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003146// "class_loader" is the class loader of the class that's referring to
3147// us. It's used to ensure that we're looking for the element type in
3148// the right context. It does NOT become the class loader for the
3149// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003150//
3151// Returns NULL with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08003152mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07003153 ConstHandle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003154 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003155 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003156 StackHandleScope<2> hs(self);
3157 Handle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, class_loader)));
3158 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003159 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003160 // We need to accept erroneous classes as component types.
Ian Rogers7b078e82014-09-10 14:44:24 -07003161 component_type.Assign(LookupClass(self, descriptor + 1, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003162 if (component_type.Get() == nullptr) {
3163 DCHECK(self->IsExceptionPending());
3164 return nullptr;
3165 } else {
3166 self->ClearException();
3167 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003168 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003169 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3170 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3171 return nullptr;
3172 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003173 // See if the component type is already loaded. Array classes are
3174 // always associated with the class loader of their underlying
3175 // element type -- an array of Strings goes with the loader for
3176 // java/lang/String -- so we need to look for it there. (The
3177 // caller should have checked for the existence of the class
3178 // before calling here, but they did so with *their* class loader,
3179 // not the component type's loader.)
3180 //
3181 // If we find it, the caller adds "loader" to the class' initiating
3182 // loader list, which should prevent us from going through this again.
3183 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003184 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003185 // are the same, because our caller (FindClass) just did the
3186 // lookup. (Even if we get this wrong we still have correct behavior,
3187 // because we effectively do this lookup again when we add the new
3188 // class to the hash table --- necessary because of possible races with
3189 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003190 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003191 mirror::Class* new_class = LookupClass(self, descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003192 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003193 return new_class;
3194 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003195 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003196
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003197 // Fill out the fields in the Class.
3198 //
3199 // It is possible to execute some methods against arrays, because
3200 // all arrays are subclasses of java_lang_Object_, so we need to set
3201 // up a vtable. We can just point at the one in java_lang_Object_.
3202 //
3203 // Array classes are simple enough that we don't need to do a full
3204 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003205 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003206 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003207 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003208 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003209 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003210 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003211 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003212 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003213 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003214 } else if (strcmp(descriptor,
3215 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003216 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003217 } else if (strcmp(descriptor,
3218 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003219 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003220 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003221 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003222 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003223 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003224 }
3225 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003226 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003227 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003228 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003229 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003230 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003231 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003232 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003233 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003234 DCHECK(new_class->GetComponentType() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003235 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003236 new_class->SetSuperClass(java_lang_Object);
3237 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003238 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003239 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003240 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
3241 new_class->PopulateEmbeddedImtAndVTable();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003242 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003243 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003244 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003245
3246
3247 // All arrays have java/lang/Cloneable and java/io/Serializable as
3248 // interfaces. We need to set that up here, so that stuff like
3249 // "instanceof" works right.
3250 //
3251 // Note: The GC could run during the call to FindSystemClass,
3252 // so we need to make sure the class object is GC-valid while we're in
3253 // there. Do this by clearing the interface list so the GC will just
3254 // think that the entries are null.
3255
3256
3257 // Use the single, global copies of "interfaces" and "iftable"
3258 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003259 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003260 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003261 CHECK(array_iftable != nullptr);
3262 new_class->SetIfTable(array_iftable);
3263 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003264
Elliott Hughes00626c22013-06-14 15:04:14 -07003265 // Inherit access flags from the component type.
3266 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3267 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3268 access_flags &= kAccJavaFlagsMask;
3269 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003270 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003271 access_flags |= kAccAbstract | kAccFinal;
3272 access_flags &= ~kAccInterface;
3273
3274 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003275
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003276 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003277 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003278 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003279 }
3280 // Another thread must have loaded the class after we
3281 // started but before we finished. Abandon what we've
3282 // done.
3283 //
3284 // (Yes, this happens.)
3285
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003286 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003287}
3288
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003289mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003290 switch (type) {
3291 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003292 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003293 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003294 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003295 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003296 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003297 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003298 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003299 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003300 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003301 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003302 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003303 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003304 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003305 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003306 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003307 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003308 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003309 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003310 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003311 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003312 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003313 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07003314 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003315}
3316
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003317mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3318 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003319 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003320 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003321 std::string source;
3322 if (dex_cache != NULL) {
3323 source += " from ";
3324 source += dex_cache->GetLocation()->ToModifiedUtf8();
3325 }
3326 LOG(INFO) << "Loaded class " << descriptor << source;
3327 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003328 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003329 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003330 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003331 if (existing != NULL) {
3332 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003333 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003334 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == NULL &&
3335 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003336 // Check a class loaded with the system class loader matches one in the image if the class
3337 // is in the image.
3338 existing = LookupClassFromImage(descriptor);
3339 if (existing != NULL) {
3340 CHECK(klass == existing);
3341 }
3342 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003343 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003344 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003345 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003346 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003347 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003348 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003349}
3350
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003351mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3352 size_t hash) {
3353 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3354 mirror::Class* existing =
3355 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3356
3357 if (existing == nullptr) {
3358 CHECK(klass->IsProxyClass());
3359 return nullptr;
3360 }
3361
3362 CHECK_NE(existing, klass) << descriptor;
3363 CHECK(!existing->IsResolved()) << descriptor;
3364 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3365
3366 for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); it != end && it->first == hash;
3367 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003368 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07003369 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003370 class_table_.erase(it);
3371 break;
3372 }
3373 }
3374
3375 CHECK(!klass->IsTemp()) << descriptor;
3376 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3377 dex_cache_image_class_lookup_required_) {
3378 // Check a class loaded with the system class loader matches one in the image if the class
3379 // is in the image.
3380 existing = LookupClassFromImage(descriptor);
3381 if (existing != nullptr) {
3382 CHECK(klass == existing) << descriptor;
3383 }
3384 }
3385 VerifyObject(klass);
3386
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003387 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003388 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003389 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003390 }
3391
3392 return existing;
3393}
3394
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003395bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003396 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003397 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07003398 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3399 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003400 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003401 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003402 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003403 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08003404 return true;
3405 }
3406 }
3407 return false;
3408}
3409
Ian Rogers7b078e82014-09-10 14:44:24 -07003410mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003411 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003412 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003413 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003414 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003415 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
3416 if (result != NULL) {
3417 return result;
3418 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003419 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003420 if (class_loader != NULL || !dex_cache_image_class_lookup_required_) {
3421 return NULL;
3422 } else {
3423 // Lookup failed but need to search dex_caches_.
3424 mirror::Class* result = LookupClassFromImage(descriptor);
3425 if (result != NULL) {
3426 InsertClass(descriptor, result, hash);
3427 } else {
3428 // Searching the image dex files/caches failed, we don't want to get into this situation
3429 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3430 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003431 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003432 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3433 MoveImageClassesToClassTable();
3434 }
3435 }
3436 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003437 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003438}
3439
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003440mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3441 const mirror::ClassLoader* class_loader,
3442 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003443 auto end = class_table_.end();
3444 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003445 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003446 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003447 if (kIsDebugBuild) {
3448 // Check for duplicates in the table.
3449 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003450 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003451 CHECK(!(klass2->GetClassLoader() == class_loader &&
3452 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003453 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3454 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003455 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003456 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003457 return klass;
3458 }
3459 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003460 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003461}
3462
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003463static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3464 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3465 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
3466 CHECK(image != NULL);
3467 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3468 return root->AsObjectArray<mirror::DexCache>();
3469}
3470
3471void ClassLinker::MoveImageClassesToClassTable() {
3472 Thread* self = Thread::Current();
3473 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3474 if (!dex_cache_image_class_lookup_required_) {
3475 return; // All dex cache classes are already in the class table.
3476 }
3477 const char* old_no_suspend_cause =
3478 self->StartAssertNoThreadSuspension("Moving image classes to class table");
3479 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003480 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003481 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3482 mirror::DexCache* dex_cache = dex_caches->Get(i);
3483 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3484 for (int32_t j = 0; j < types->GetLength(); j++) {
3485 mirror::Class* klass = types->Get(j);
3486 if (klass != NULL) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003487 DCHECK(klass->GetClassLoader() == NULL);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003488 const char* descriptor = klass->GetDescriptor(&temp);
3489 size_t hash = Hash(descriptor);
3490 mirror::Class* existing = LookupClassFromTableLocked(descriptor, NULL, hash);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003491 if (existing != NULL) {
3492 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3493 << PrettyClassAndClassLoader(klass);
3494 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003495 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003496 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003497 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003498 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003499 }
3500 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003501 }
3502 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003503 dex_cache_image_class_lookup_required_ = false;
3504 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3505}
3506
3507mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
3508 Thread* self = Thread::Current();
3509 const char* old_no_suspend_cause =
3510 self->StartAssertNoThreadSuspension("Image class lookup");
3511 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3512 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3513 mirror::DexCache* dex_cache = dex_caches->Get(i);
3514 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003515 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003516 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
3517 if (string_id != NULL) {
3518 const DexFile::TypeId* type_id =
3519 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
3520 if (type_id != NULL) {
3521 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3522 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
3523 if (klass != NULL) {
3524 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3525 return klass;
3526 }
3527 }
3528 }
3529 }
3530 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3531 return NULL;
3532}
3533
3534void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3535 result.clear();
3536 if (dex_cache_image_class_lookup_required_) {
3537 MoveImageClassesToClassTable();
3538 }
3539 size_t hash = Hash(descriptor);
3540 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003541 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003542 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003543 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003544 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003545 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003546 }
3547 }
3548}
3549
Ian Rogers7b078e82014-09-10 14:44:24 -07003550void ClassLinker::VerifyClass(Thread* self, ConstHandle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003551 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003552 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003553
Ian Rogers9ffb0392012-09-10 11:56:50 -07003554 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003555 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003556 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003557 return;
3558 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003559 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3560 return;
3561 }
jeffhao98eacac2011-09-14 16:11:53 -07003562
Ian Rogers9ffb0392012-09-10 11:56:50 -07003563 // The class might already be erroneous, for example at compile time if we attempted to verify
3564 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003565 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003566 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003567 return;
3568 }
3569
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003570 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003571 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003572 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003573 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003574 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003575 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003576 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003577 }
jeffhao98eacac2011-09-14 16:11:53 -07003578
Jeff Hao4a200f52014-04-01 14:58:49 -07003579 // Skip verification if disabled.
3580 if (!Runtime::Current()->IsVerificationEnabled()) {
3581 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003582 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003583 return;
3584 }
3585
Ian Rogers9ffb0392012-09-10 11:56:50 -07003586 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003587 StackHandleScope<2> hs(self);
3588 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
3589 if (super.Get() != NULL) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003590 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003591 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003592
3593 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003594 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003595 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003596 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003597 std::string error_msg(
3598 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3599 PrettyDescriptor(klass.Get()).c_str(),
3600 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003601 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003602 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3603 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003604 self->ClearException();
3605 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003606 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3607 if (cause.Get() != nullptr) {
3608 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003609 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003610 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003611 if (Runtime::Current()->IsCompiler()) {
3612 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3613 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003614 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003615 return;
3616 }
3617 }
3618
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003619 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003620 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003621 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003622 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003623 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003624 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003625 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003626 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003627 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3628 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003629 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003630 return;
3631 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003632 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003633 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003634 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003635 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003636 Runtime::Current()->IsCompiler(),
3637 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003638 }
3639 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003640 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003641 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003642 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3643 << " because: " << error_msg;
3644 }
Ian Rogers1f539342012-10-03 21:09:42 -07003645 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003646 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003647 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003648 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003649 // Even though there were no verifier failures we need to respect whether the super-class
3650 // was verified or requiring runtime reverification.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003651 if (super.Get() == NULL || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003652 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003653 } else {
3654 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003655 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003656 // Pretend a soft failure occured so that we don't consider the class verified below.
3657 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003658 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003659 } else {
3660 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3661 // Soft failures at compile time should be retried at runtime. Soft
3662 // failures at runtime will be handled by slow paths in the generated
3663 // code. Set status accordingly.
3664 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003665 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003666 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003667 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003668 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3669 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003670 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003671 }
3672 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003673 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003674 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003675 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3676 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003677 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003678 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003679 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003680 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003681 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003682 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003683 // Let the interpreter know it by setting the kAccPreverified flag onto each
3684 // method.
3685 // Note: we're going here during compilation and at runtime. When we set the
3686 // kAccPreverified flag when compiling image classes, the flag is recorded
3687 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003688 EnsurePreverifiedMethods(klass);
3689 }
3690}
3691
3692void ClassLinker::EnsurePreverifiedMethods(ConstHandle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003693 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003694 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003695 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003696 }
jeffhao98eacac2011-09-14 16:11:53 -07003697}
3698
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003699bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3700 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003701 // If we're compiling, we can only verify the class using the oat file if
3702 // we are not compiling the image or if the class we're verifying is not part of
3703 // the app. In other words, we will only check for preverification of bootclasspath
3704 // classes.
3705 if (Runtime::Current()->IsCompiler()) {
3706 // Are we compiling the bootclasspath?
3707 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3708 return false;
3709 }
3710 // We are compiling an app (not the image).
3711
3712 // Is this an app class? (I.e. not a bootclasspath class)
3713 if (klass->GetClassLoader() != NULL) {
3714 return false;
3715 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003716 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003717
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003718 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003719 // Make this work with gtests, which do not set up the image properly.
3720 // TODO: we should clean up gtests to set up the image path properly.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003721 if (Runtime::Current()->IsCompiler() || (oat_dex_file == nullptr)) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003722 return false;
3723 }
3724
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003725 CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003726 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003727 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003728 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3729 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003730 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003731 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003732 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003733 // Compile time verification failed with a soft error. Compile time verification can fail
3734 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003735 // class ... {
3736 // Foo x;
3737 // .... () {
3738 // if (...) {
3739 // v1 gets assigned a type of resolved class Foo
3740 // } else {
3741 // v1 gets assigned a type of unresolved class Bar
3742 // }
3743 // iput x = v1
3744 // } }
3745 // when we merge v1 following the if-the-else it results in Conflict
3746 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3747 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3748 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3749 // at compile time).
3750 return false;
3751 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003752 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003753 // Compile time verification failed with a hard error. This is caused by invalid instructions
3754 // in the class. These errors are unrecoverable.
3755 return false;
3756 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003757 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003758 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3759 // not loading the class.
3760 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3761 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003762 return false;
3763 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003764 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003765 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003766 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003767 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003768
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003769 return false;
3770}
3771
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003772void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07003773 ConstHandle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003774 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3775 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3776 }
3777 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3778 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3779 }
3780}
3781
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003782void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003783 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003784 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3785 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
3786 if (code_item == NULL) {
3787 return; // native or abstract method
3788 }
3789 if (code_item->tries_size_ == 0) {
3790 return; // nothing to process
3791 }
3792 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
3793 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3794 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3795 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3796 CatchHandlerIterator iterator(handlers_ptr);
3797 for (; iterator.HasNext(); iterator.Next()) {
3798 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3799 // unresolved exception types will be ignored by exception delivery
3800 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003801 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003802 if (exception_type == NULL) {
3803 DCHECK(Thread::Current()->IsExceptionPending());
3804 Thread::Current()->ClearException();
3805 }
3806 }
3807 }
3808 handlers_ptr = iterator.EndDataPointer();
3809 }
3810}
3811
Brian Carlstromea46f952013-07-30 01:26:50 -07003812static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Mathieu Chartierbf99f772014-08-23 16:37:27 -07003813static void CheckProxyMethod(ConstHandle<mirror::ArtMethod> method,
3814 ConstHandle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003815
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003816mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003817 jobjectArray interfaces, jobject loader,
3818 jobjectArray methods, jobjectArray throws) {
3819 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003820 StackHandleScope<8> hs(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003821 Handle<mirror::Class> klass(hs.NewHandle(
3822 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003823 if (klass.Get() == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003824 CHECK(self->IsExceptionPending()); // OOME.
3825 return NULL;
3826 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003827 DCHECK(klass->GetClass() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003828 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003829 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3830 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003831 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003832 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003833 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003834 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003835 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003836 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003837
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003838 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003839 {
3840 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
3841 if (UNLIKELY(sfields == NULL)) {
3842 CHECK(self->IsExceptionPending()); // OOME.
3843 return NULL;
3844 }
3845 klass->SetSFields(sfields);
3846 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003847 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3848 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003849 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3850 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003851 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003852 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003853 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003854 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003855 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003856 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003857 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3858 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003859 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3860 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003861 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003862 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003863 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003864 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003865 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003866 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003867 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003868
Ian Rogers466bb252011-10-14 03:29:56 -07003869 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003870 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003871 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003872 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003873 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003874 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003875 }
3876 klass->SetDirectMethods(directs);
3877 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003878 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003879 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003880 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003881 }
3882 klass->SetDirectMethod(0, constructor);
3883 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003884
Mathieu Chartier590fee92013-09-13 13:46:47 -07003885 // Create virtual method using specified prototypes.
3886 size_t num_virtual_methods =
3887 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003888 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003889 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3890 num_virtual_methods);
Ian Rogersa436fde2013-08-27 23:34:06 -07003891 if (UNLIKELY(virtuals == NULL)) {
3892 CHECK(self->IsExceptionPending()); // OOME.
3893 return NULL;
3894 }
3895 klass->SetVirtualMethods(virtuals);
3896 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003897 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003898 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003899 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3900 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003901 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003902 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003903 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003904 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003905 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003906 }
3907 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003908 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003909
3910 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003911 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003912 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003913
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003914 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3915 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003916 {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003917 ObjectLock<mirror::Class> resolution_lock(self, klass); // Must hold lock on object when resolved.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003918 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003919 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003920 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003921 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003922 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003923 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003924 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003925 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003926
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003927 CHECK(klass->IsRetired());
3928 CHECK_NE(klass.Get(), new_class);
3929 klass.Assign(new_class);
3930
3931 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
3932 interfaces_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3933 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
3934 throws_sfield->SetObject<false>(klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
3935
3936 {
3937 // Lock on klass is released. Lock new class object.
3938 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003939 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003940 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003941
3942 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003943 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003944 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003945 CheckProxyConstructor(klass->GetDirectMethod(0));
3946 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003947 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003948 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3949 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003950 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003951 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3952 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003953 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003954
Mathieu Chartier590fee92013-09-13 13:46:47 -07003955 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003956 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003957 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003958 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3959
3960 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003961 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003962 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003963
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003964 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003965 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003966 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003967 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003968 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003969 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003970 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003971 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003972}
3973
Ian Rogersef7d42f2014-01-06 12:55:46 -08003974std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003975 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003976 mirror::String* name = proxy_class->GetName();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003977 DCHECK(name != NULL);
3978 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3979}
3980
Ian Rogersef7d42f2014-01-06 12:55:46 -08003981mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3982 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003983 DCHECK(proxy_class->IsProxyClass());
3984 DCHECK(proxy_method->IsProxyMethod());
3985 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003986 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003987 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003988 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003989 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003990 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003991 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003992 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003993 break;
3994 }
3995 }
3996 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003997 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003998 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003999 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07004000 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08004001 return resolved_method;
4002}
4003
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004004
Brian Carlstromea46f952013-07-30 01:26:50 -07004005mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004006 ConstHandle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07004007 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07004008 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07004009 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004010 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07004011 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
4012 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02004013 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4014 // constructor method.
4015 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
4016 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07004017 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4018 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07004019 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
4020 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004021 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07004022 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004023 }
Ian Rogers466bb252011-10-14 03:29:56 -07004024 // Make this constructor public and fix the class to be our Proxy version
4025 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004026 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004027 return constructor;
4028}
4029
Brian Carlstromea46f952013-07-30 01:26:50 -07004030static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004031 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004032 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004033 CHECK_STREQ(constructor->GetName(), "<init>");
4034 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4035 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004036 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004037}
4038
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004039mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004040 ConstHandle<mirror::Class> klass,
4041 ConstHandle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004042 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4043 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004044 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004045 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004046 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004047 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004048 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Ian Rogersa436fde2013-08-27 23:34:06 -07004049 if (UNLIKELY(method == NULL)) {
4050 CHECK(self->IsExceptionPending()); // OOME.
4051 return NULL;
4052 }
Ian Rogers466bb252011-10-14 03:29:56 -07004053
4054 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4055 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004056 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004057 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004058
Ian Rogers466bb252011-10-14 03:29:56 -07004059 // At runtime the method looks like a reference and argument saving method, clone the code
4060 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004061 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4062 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004063 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004064
Ian Rogersc2b44472011-12-14 21:17:17 -08004065 return method;
4066}
Jesse Wilson95caa792011-10-12 18:14:17 -04004067
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004068static void CheckProxyMethod(ConstHandle<mirror::ArtMethod> method,
4069 ConstHandle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004070 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004071 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004072 CHECK(!prototype->IsFinal());
4073 CHECK(method->IsFinal());
4074 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004075
4076 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4077 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4078 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004079 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4080 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004081 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4082
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004083 StackHandleScope<2> hs(Thread::Current());
4084 MethodHelper mh(hs.NewHandle(method.Get()));
4085 MethodHelper mh2(hs.NewHandle(prototype.Get()));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004086 CHECK_STREQ(method->GetName(), prototype->GetName());
4087 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004088 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08004089 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004090}
4091
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004092static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4093 bool can_init_parents)
4094 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004095 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004096 return true;
4097 }
4098 if (!can_init_statics) {
4099 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004100 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004101 if (clinit != NULL) {
4102 return false;
4103 }
4104 // Check if there are encoded static values needing initialization.
4105 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004106 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004107 DCHECK(dex_class_def != NULL);
4108 if (dex_class_def->static_values_off_ != 0) {
4109 return false;
4110 }
4111 }
4112 }
4113 if (!klass->IsInterface() && klass->HasSuperClass()) {
4114 mirror::Class* super_class = klass->GetSuperClass();
4115 if (!can_init_parents && !super_class->IsInitialized()) {
4116 return false;
4117 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004118 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004119 return false;
4120 }
4121 }
4122 }
4123 return true;
4124}
4125
Ian Rogers7b078e82014-09-10 14:44:24 -07004126bool ClassLinker::InitializeClass(Thread* self, ConstHandle<mirror::Class> klass,
4127 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004128 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4129
4130 // Are we already initialized and therefore done?
4131 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4132 // an initialized class will never change its state.
4133 if (klass->IsInitialized()) {
4134 return true;
4135 }
4136
4137 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004138 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004139 return false;
4140 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004141
Ian Rogers7b078e82014-09-10 14:44:24 -07004142 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004143 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004144 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004145 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004146
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004147 // Re-check under the lock in case another thread initialized ahead of us.
4148 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004149 return true;
4150 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004151
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004152 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004153 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004154 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004155 return false;
4156 }
4157
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004158 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004159
4160 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004161 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004162 if (!klass->IsVerified()) {
4163 // We failed to verify, expect either the klass to be erroneous or verification failed at
4164 // compile time.
4165 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004166 CHECK(self->IsExceptionPending());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004167 } else {
4168 CHECK(Runtime::Current()->IsCompiler());
4169 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004170 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004171 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004172 } else {
4173 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004174 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004175 }
4176
Brian Carlstromd1422f82011-09-28 11:37:09 -07004177 // If the class is kStatusInitializing, either this thread is
4178 // initializing higher up the stack or another thread has beat us
4179 // to initializing and we need to wait. Either way, this
4180 // invocation of InitializeClass will not be responsible for
4181 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004182 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004183 // Could have got an exception during verification.
4184 if (self->IsExceptionPending()) {
4185 return false;
4186 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004187 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004188 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004189 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004190 return true;
4191 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004192 // No. That's fine. Wait for another thread to finish initializing.
4193 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004194 }
4195
4196 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004197 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004198 return false;
4199 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004200 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004201
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004202 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004203
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004204 // From here out other threads may observe that we're initializing and so changes of state
4205 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004206 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004207 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004208
4209 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004210 }
4211
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004212 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004213 if (!klass->IsInterface() && klass->HasSuperClass()) {
4214 mirror::Class* super_class = klass->GetSuperClass();
4215 if (!super_class->IsInitialized()) {
4216 CHECK(!super_class->IsInterface());
4217 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004218 StackHandleScope<1> hs(self);
4219 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004220 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004221 if (!super_initialized) {
4222 // The super class was verified ahead of entering initializing, we should only be here if
4223 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004224 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004225 << "Super class initialization failed for "
4226 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004227 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004228 << "\nPending exception:\n"
4229 << (self->GetException(NULL) != NULL ? self->GetException(NULL)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004230 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004231 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004232 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004233 return false;
4234 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004235 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004236 }
4237
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004238 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004239 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004240 CHECK(dex_class_def != NULL);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004241 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004242 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004243 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004244 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004245 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4246 this, *dex_class_def);
4247 const byte* class_data = dex_file.GetClassData(*dex_class_def);
4248 ClassDataItemIterator field_it(dex_file, class_data);
4249 if (value_it.HasNext()) {
4250 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004251 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004252 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004253 StackHandleScope<1> hs(self);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004254 Handle<mirror::ArtField> field(hs.NewHandle(
4255 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004256 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004257 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004258 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004259 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004260 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004261 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004262 }
4263 }
4264 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004265
Ian Rogersd91d6d62013-09-25 20:26:14 -07004266 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004267 if (clinit != NULL) {
4268 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004269 JValue result;
4270 clinit->Invoke(self, NULL, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004271 }
4272
Ian Rogers7b078e82014-09-10 14:44:24 -07004273 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004274 uint64_t t1 = NanoTime();
4275
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004276 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004277 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004278 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004279
4280 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07004281 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004282 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004283 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004284 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004285 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4286 RuntimeStats* thread_stats = self->GetStats();
4287 ++global_stats->class_init_count;
4288 ++thread_stats->class_init_count;
4289 global_stats->class_init_time_ns += (t1 - t0);
4290 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004291 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004292 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004293 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004294 std::string temp;
4295 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004296 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004297 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004298 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004299 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004300 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004301 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004302 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004303}
4304
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004305bool ClassLinker::WaitForInitializeClass(ConstHandle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004306 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004307 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004308 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004309 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004310 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004311 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004312
4313 // When we wake up, repeat the test for init-in-progress. If
4314 // there's an exception pending (only possible if
4315 // "interruptShouldThrow" was set), bail out.
4316 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07004317 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004318 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004319 return false;
4320 }
4321 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004322 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004323 continue;
4324 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004325 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004326 // Compile time initialization failed.
4327 return false;
4328 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004329 if (klass->IsErroneous()) {
4330 // The caller wants an exception, but it was thrown in a
4331 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004332 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004333 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004334 return false;
4335 }
4336 if (klass->IsInitialized()) {
4337 return true;
4338 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004339 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004340 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004341 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004342 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004343}
4344
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004345bool ClassLinker::ValidateSuperClassDescriptors(ConstHandle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004346 if (klass->IsInterface()) {
4347 return true;
4348 }
Ian Rogers151f2212014-05-06 11:27:27 -07004349 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004350 StackHandleScope<2> hs(Thread::Current());
4351 MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4352 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004353 if (klass->HasSuperClass() &&
4354 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004355 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4356 mh.ChangeMethod(klass->GetVTableEntry(i));
4357 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004358 if (mh.GetMethod() != super_mh.GetMethod() &&
4359 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4360 ThrowLinkageError(klass.Get(),
4361 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004362 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004363 PrettyMethod(mh.GetMethod()).c_str(),
4364 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004365 return false;
4366 }
4367 }
4368 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004369 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004370 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4371 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4372 for (uint32_t j = 0; j < num_methods; ++j) {
4373 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4374 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004375 if (mh.GetMethod() != super_mh.GetMethod() &&
4376 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4377 ThrowLinkageError(klass.Get(),
4378 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004379 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004380 PrettyMethod(mh.GetMethod()).c_str(),
4381 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004382 return false;
4383 }
4384 }
4385 }
4386 }
4387 return true;
4388}
4389
Ian Rogers7b078e82014-09-10 14:44:24 -07004390bool ClassLinker::EnsureInitialized(Thread* self, ConstHandle<mirror::Class> c,
4391 bool can_init_fields, bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004392 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004393 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004394 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004395 return true;
4396 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004397 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004398 if (!success) {
4399 if (can_init_fields && can_init_parents) {
4400 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4401 }
4402 } else {
4403 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004404 }
4405 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004406}
4407
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004408void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4409 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4410 if (fields != nullptr) {
4411 for (int index = 0; index < fields->GetLength(); index ++) {
4412 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4413 fields->Get(index)->SetDeclaringClass(new_class);
4414 }
4415 }
4416 }
4417
4418 fields = new_class->GetSFields();
4419 if (fields != nullptr) {
4420 for (int index = 0; index < fields->GetLength(); index ++) {
4421 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4422 fields->Get(index)->SetDeclaringClass(new_class);
4423 }
4424 }
4425 }
4426
4427 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4428 if (methods != nullptr) {
4429 for (int index = 0; index < methods->GetLength(); index ++) {
4430 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4431 methods->Get(index)->SetDeclaringClass(new_class);
4432 }
4433 }
4434 }
4435
4436 methods = new_class->GetVirtualMethods();
4437 if (methods != nullptr) {
4438 for (int index = 0; index < methods->GetLength(); index ++) {
4439 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4440 methods->Get(index)->SetDeclaringClass(new_class);
4441 }
4442 }
4443 }
4444}
4445
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004446bool ClassLinker::LinkClass(Thread* self, const char* descriptor, ConstHandle<mirror::Class> klass,
4447 ConstHandle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004448 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004449 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004450
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004451 if (!LinkSuperClass(klass)) {
4452 return false;
4453 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004454 if (!LinkMethods(self, klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004455 return false;
4456 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004457 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004458 return false;
4459 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004460 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004461 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004462 return false;
4463 }
4464 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004465 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004466
4467 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4468 // We don't need to retire this class as it has no embedded tables or it was created the
4469 // correct size during class linker initialization.
4470 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4471
4472 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4473 klass->PopulateEmbeddedImtAndVTable();
4474 }
4475
4476 // This will notify waiters on klass that saw the not yet resolved
4477 // class in the class_table_ during EnsureResolved.
4478 klass->SetStatus(mirror::Class::kStatusResolved, self);
4479 *new_class = klass.Get();
4480 } else {
4481 CHECK(!klass->IsResolved());
4482 // Retire the temporary class and create the correctly sized resolved class.
4483 *new_class = klass->CopyOf(self, class_size);
4484 if (UNLIKELY(*new_class == NULL)) {
4485 CHECK(self->IsExceptionPending()); // Expect an OOME.
4486 klass->SetStatus(mirror::Class::kStatusError, self);
4487 return false;
4488 }
4489
4490 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4491 StackHandleScope<1> hs(self);
4492 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4493 ObjectLock<mirror::Class> lock(self, new_class_h);
4494
4495 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4496
4497 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
4498 CHECK(existing == NULL || existing == klass.Get());
4499
4500 // This will notify waiters on temp class that saw the not yet resolved class in the
4501 // class_table_ during EnsureResolved.
4502 klass->SetStatus(mirror::Class::kStatusRetired, self);
4503
4504 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4505 // This will notify waiters on new_class that saw the not yet resolved
4506 // class in the class_table_ during EnsureResolved.
4507 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004508 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004509 return true;
4510}
4511
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004512bool ClassLinker::LoadSuperAndInterfaces(ConstHandle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004513 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004514 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4515 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004516 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004517 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004518 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004519 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004520 return false;
4521 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004522 // Verify
4523 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004524 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004525 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004526 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004527 return false;
4528 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004529 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004530 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004531 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004532 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004533 if (interfaces != NULL) {
4534 for (size_t i = 0; i < interfaces->Size(); i++) {
4535 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004536 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004537 if (interface == NULL) {
4538 DCHECK(Thread::Current()->IsExceptionPending());
4539 return false;
4540 }
4541 // Verify
4542 if (!klass->CanAccess(interface)) {
4543 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004544 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004545 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004546 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004547 return false;
4548 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004549 }
4550 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004551 // Mark the class as loaded.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004552 klass->SetStatus(mirror::Class::kStatusLoaded, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004553 return true;
4554}
4555
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004556bool ClassLinker::LinkSuperClass(ConstHandle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004557 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004558 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004559 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004560 if (super != NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004561 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004562 return false;
4563 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004564 return true;
4565 }
4566 if (super == NULL) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004567 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4568 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004569 return false;
4570 }
4571 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004572 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004573 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004574 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004575 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004576 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004577 return false;
4578 }
4579 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004580 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004581 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004582 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004583 return false;
4584 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004585
Brian Carlstromf3632832014-05-20 15:36:53 -07004586 // Inherit kAccClassIsFinalizable from the superclass in case this
4587 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004588 if (super->IsFinalizable()) {
4589 klass->SetFinalizable();
4590 }
4591
Elliott Hughes2da50362011-10-10 16:57:08 -07004592 // Inherit reference flags (if any) from the superclass.
4593 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4594 if (reference_flags != 0) {
4595 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4596 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004597 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004598 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004599 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004600 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004601 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004602 return false;
4603 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004604
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004605 if (kIsDebugBuild) {
4606 // Ensure super classes are fully resolved prior to resolving fields..
4607 while (super != NULL) {
4608 CHECK(super->IsResolved());
4609 super = super->GetSuperClass();
4610 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004611 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004612 return true;
4613}
4614
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004615// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004616bool ClassLinker::LinkMethods(Thread* self, ConstHandle<mirror::Class> klass,
4617 ConstHandle<mirror::ObjectArray<mirror::Class>> interfaces) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004618 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004619 if (klass->IsInterface()) {
4620 // No vtable.
4621 size_t count = klass->NumVirtualMethods();
4622 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004623 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004624 return false;
4625 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004626 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004627 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004628 }
jeffhaobdb76512011-09-07 11:43:16 -07004629 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004630 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004631 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07004632 // Link virtual and interface method tables
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004633 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004634 }
4635 return true;
4636}
4637
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004638bool ClassLinker::LinkVirtualMethods(Thread* self, ConstHandle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004639 if (klass->HasSuperClass()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004640 uint32_t max_count = klass->NumVirtualMethods() +
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004641 klass->GetSuperClass()->GetVTableLength();
4642 size_t actual_count = klass->GetSuperClass()->GetVTableLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004643 CHECK_LE(actual_count, max_count);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004644 StackHandleScope<4> hs(self);
4645 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004646 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004647 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4648 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4649 if (UNLIKELY(vtable.Get() == nullptr)) {
4650 CHECK(self->IsExceptionPending()); // OOME.
4651 return false;
4652 }
4653 int len = super_class->GetVTableLength();
Mingyao Yang1a128582014-07-22 17:33:25 -07004654 for (int i = 0; i < len; i++) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004655 vtable->Set<false>(i, super_class->GetVTableEntry(i));
4656 }
4657 } else {
Mingyao Yang38eecb02014-08-13 14:51:03 -07004658 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004659 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4660 if (UNLIKELY(vtable.Get() == nullptr)) {
4661 CHECK(self->IsExceptionPending()); // OOME.
4662 return false;
4663 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004664 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004665
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004666 // See if any of our virtual methods override the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004667 MethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4668 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004669 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004670 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004671 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004672 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004673 for (; j < actual_count; ++j) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004674 mirror::ArtMethod* super_method = vtable->Get(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004675 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004676 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004677 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4678 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004679 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004680 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004681 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004682 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004683 return false;
4684 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004685 vtable->Set<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004686 local_method->SetMethodIndex(j);
4687 break;
4688 } else {
4689 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4690 << " would have incorrectly overridden the package-private method in "
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004691 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004692 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004693 }
4694 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004695 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004696 // Not overriding, append.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004697 vtable->Set<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004698 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004699 actual_count += 1;
4700 }
4701 }
4702 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004703 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004704 return false;
4705 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004706 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004707 CHECK_LE(actual_count, max_count);
4708 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004709 vtable.Assign(vtable->CopyOf(self, actual_count));
4710 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004711 CHECK(self->IsExceptionPending()); // OOME.
4712 return false;
4713 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004714 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004715 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004716 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004717 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004718 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004719 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004720 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004721 return false;
4722 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004723 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004724 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004725 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
4726 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004727 CHECK(self->IsExceptionPending()); // OOME.
4728 return false;
4729 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004730 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004731 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004732 vtable->Set<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004733 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004734 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004735 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004736 }
4737 return true;
4738}
4739
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004740bool ClassLinker::LinkInterfaceMethods(ConstHandle<mirror::Class> klass,
4741 ConstHandle<mirror::ObjectArray<mirror::Class>> interfaces) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004742 Thread* const self = Thread::Current();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004743 Runtime* const runtime = Runtime::Current();
Jeff Hao88474b42013-10-23 16:24:40 -07004744 // Set the imt table to be all conflicts by default.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004745 klass->SetImTable(runtime->GetDefaultImt());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004746 size_t super_ifcount;
4747 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004748 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004749 } else {
4750 super_ifcount = 0;
4751 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07004752 uint32_t num_interfaces =
4753 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4754 size_t ifcount = super_ifcount + num_interfaces;
4755 for (size_t i = 0; i < num_interfaces; i++) {
4756 mirror::Class* interface =
4757 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4758 interfaces->Get(i);
4759 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004760 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004761 if (ifcount == 0) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004762 // Class implements no interfaces.
4763 DCHECK_EQ(klass->GetIfTableCount(), 0);
4764 DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004765 return true;
4766 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004767 if (ifcount == super_ifcount) {
4768 // Class implements same interfaces as parent, are any of these not marker interfaces?
4769 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004770 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Ian Rogers9bc81912012-10-11 21:43:36 -07004771 for (size_t i = 0; i < ifcount; ++i) {
4772 if (super_iftable->GetMethodArrayCount(i) > 0) {
4773 has_non_marker_interface = true;
4774 break;
4775 }
4776 }
4777 if (!has_non_marker_interface) {
4778 // Class just inherits marker interfaces from parent so recycle parent's iftable.
4779 klass->SetIfTable(super_iftable);
4780 return true;
4781 }
4782 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004783 StackHandleScope<5> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004784 Handle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
4785 if (UNLIKELY(iftable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004786 CHECK(self->IsExceptionPending()); // OOME.
4787 return false;
4788 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004789 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004790 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004791 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004792 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004793 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004794 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004795 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004796 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004797 // Flatten the interface inheritance hierarchy.
4798 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004799 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004800 mirror::Class* interface =
Mathieu Chartierf8322842014-05-16 10:59:25 -07004801 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4802 interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004803 DCHECK(interface != NULL);
4804 if (!interface->IsInterface()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004805 std::string temp;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004806 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4807 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers1ff3c982014-08-12 02:30:58 -07004808 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004809 return false;
4810 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004811 // Check if interface is already in iftable
4812 bool duplicate = false;
4813 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004814 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004815 if (existing_interface == interface) {
4816 duplicate = true;
4817 break;
4818 }
4819 }
4820 if (!duplicate) {
4821 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004822 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004823 // Add this interface's non-duplicate super-interfaces.
4824 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004825 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004826 bool super_duplicate = false;
4827 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004828 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004829 if (existing_interface == super_interface) {
4830 super_duplicate = true;
4831 break;
4832 }
4833 }
4834 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004835 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004836 }
4837 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004838 }
4839 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004840 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004841 // Shrink iftable in case duplicates were found
4842 if (idx < ifcount) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004843 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
4844 if (UNLIKELY(iftable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004845 CHECK(self->IsExceptionPending()); // OOME.
4846 return false;
4847 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004848 ifcount = idx;
4849 } else {
4850 CHECK_EQ(idx, ifcount);
4851 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004852 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004853
4854 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004855 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004856 return true;
4857 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004858 self->AllowThreadSuspension();
Jeff Hao88474b42013-10-23 16:24:40 -07004859 // Allocate imtable
4860 bool imtable_changed = false;
Ian Rogers700a4022014-05-19 16:49:03 -07004861 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004862 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004863 if (UNLIKELY(imtable.Get() == NULL)) {
Jeff Hao88474b42013-10-23 16:24:40 -07004864 CHECK(self->IsExceptionPending()); // OOME.
4865 return false;
4866 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004867 MethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4868 MethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004869 size_t max_miranda_methods = 0; // The max size of miranda_list.
4870 for (size_t i = 0; i < ifcount; ++i) {
4871 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4872 }
4873 Handle<mirror::ObjectArray<mirror::ArtMethod>>
4874 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
4875 size_t miranda_list_size = 0; // The current size of miranda_list.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004876 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004877 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004878 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004879 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004880 StackHandleScope<2> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004881 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004882 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4883 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004884 CHECK(self->IsExceptionPending()); // OOME.
4885 return false;
4886 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004887 iftable->SetMethodArray(i, method_array.Get());
Ian Rogers700a4022014-05-19 16:49:03 -07004888 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004889 hs.NewHandle(klass->GetVTableDuringLinking()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004890 for (size_t j = 0; j < num_methods; ++j) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004891 interface_mh.ChangeMethod(iftable->GetInterface(i)->GetVirtualMethod(j));
Ian Rogers9bc81912012-10-11 21:43:36 -07004892 int32_t k;
4893 // For each method listed in the interface's method list, find the
4894 // matching method in our class's method list. We want to favor the
4895 // subclass over the superclass, which just requires walking
4896 // back from the end of the vtable. (This only matters if the
4897 // superclass defines a private method and this class redefines
4898 // it -- otherwise it would use the same vtable slot. In .dex files
4899 // those don't end up in the virtual method table, so it shouldn't
4900 // matter which direction we go. We walk it backward anyway.)
4901 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004902 vtable_mh.ChangeMethod(vtable->Get(k));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004903 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004904 if (!vtable_mh.Get()->IsAbstract() && !vtable_mh.Get()->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004905 ThrowIllegalAccessError(
4906 klass.Get(),
4907 "Method '%s' implementing interface method '%s' is not public",
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004908 PrettyMethod(vtable_mh.Get()).c_str(),
4909 PrettyMethod(interface_mh.Get()).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004910 return false;
4911 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004912 method_array->Set<false>(j, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004913 // Place method in imt if entry is empty, place conflict otherwise.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004914 uint32_t imt_index = interface_mh.Get()->GetDexMethodIndex() % mirror::Class::kImtSize;
Jeff Hao88474b42013-10-23 16:24:40 -07004915 if (imtable->Get(imt_index) == NULL) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004916 imtable->Set<false>(imt_index, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004917 imtable_changed = true;
4918 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004919 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -07004920 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004921 break;
4922 }
4923 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004924 if (k < 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004925 StackHandleScope<1> hs(self);
4926 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004927 for (size_t l = 0; l < miranda_list_size; ++l) {
4928 mirror::ArtMethod* mir_method = miranda_list->Get(l);
4929 DCHECK(mir_method != nullptr);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004930 vtable_mh.ChangeMethod(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004931 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004932 miranda_method.Assign(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004933 break;
4934 }
4935 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004936 if (miranda_method.Get() == NULL) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004937 // Point the interface table at a phantom slot.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004938 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_mh.Get()->Clone(self)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004939 if (UNLIKELY(miranda_method.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004940 CHECK(self->IsExceptionPending()); // OOME.
4941 return false;
4942 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004943 DCHECK_LT(miranda_list_size, max_miranda_methods);
4944 miranda_list->Set<false>(miranda_list_size++, miranda_method.Get());
Ian Rogers9bc81912012-10-11 21:43:36 -07004945 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004946 method_array->Set<false>(j, miranda_method.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004947 }
4948 }
4949 }
4950 }
Jeff Hao88474b42013-10-23 16:24:40 -07004951 if (imtable_changed) {
4952 // Fill in empty entries in interface method table with conflict.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004953 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004954 for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
Jeff Hao88474b42013-10-23 16:24:40 -07004955 if (imtable->Get(i) == NULL) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004956 imtable->Set<false>(i, imt_conflict_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004957 }
4958 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004959 klass->SetImTable(imtable.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004960 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004961 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004962 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004963 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004964 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4965 if (old_method_count == 0) {
4966 virtuals = AllocArtMethodArray(self, new_method_count);
4967 } else {
4968 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4969 }
4970 if (UNLIKELY(virtuals == NULL)) {
4971 CHECK(self->IsExceptionPending()); // OOME.
4972 return false;
4973 }
4974 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004975
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004976 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004977 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004978 hs.NewHandle(klass->GetVTableDuringLinking()));
4979 CHECK(vtable.Get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004980 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004981 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004982 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
4983 if (UNLIKELY(vtable.Get() == NULL)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004984 CHECK(self->IsExceptionPending()); // OOME.
4985 return false;
4986 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004987 for (size_t i = 0; i < miranda_list_size; ++i) {
4988 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004989 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004990 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4991 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4992 klass->SetVirtualMethod(old_method_count + i, method);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004993 vtable->Set<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004994 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004995 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004996 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004997 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004998
Brian Carlstromea46f952013-07-30 01:26:50 -07004999 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07005000 for (int i = 0; i < vtable->GetLength(); ++i) {
5001 CHECK(vtable->Get(i) != NULL);
5002 }
5003
Ian Rogers7b078e82014-09-10 14:44:24 -07005004 self->AllowThreadSuspension();
Elliott Hughes4681c802011-09-25 18:04:37 -07005005
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005006 return true;
5007}
5008
Ian Rogers7b078e82014-09-10 14:44:24 -07005009bool ClassLinker::LinkInstanceFields(Thread* self, ConstHandle<mirror::Class> klass) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005010 CHECK(klass.Get() != NULL);
Ian Rogers7b078e82014-09-10 14:44:24 -07005011 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005012}
5013
Ian Rogers7b078e82014-09-10 14:44:24 -07005014bool ClassLinker::LinkStaticFields(Thread* self, ConstHandle<mirror::Class> klass, size_t* class_size) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005015 CHECK(klass.Get() != NULL);
Ian Rogers7b078e82014-09-10 14:44:24 -07005016 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005017}
5018
Brian Carlstromdbc05252011-09-09 01:59:59 -07005019struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005020 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5021 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005022 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005023 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005024 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005025 // 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 -07005026 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5027 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005028 if (type1 != type2) {
5029 bool is_primitive1 = type1 != Primitive::kPrimNot;
5030 bool is_primitive2 = type2 != Primitive::kPrimNot;
Fred Shih37f05ef2014-07-16 18:38:08 -07005031 if (type1 != type2) {
5032 if (is_primitive1 && is_primitive2) {
5033 // Larger primitive types go first.
5034 return Primitive::ComponentSize(type1) > Primitive::ComponentSize(type2);
5035 } else {
5036 // Reference always goes first.
5037 return !is_primitive1;
5038 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08005039 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005040 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005041 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005042 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005043 }
5044};
5045
Ian Rogers7b078e82014-09-10 14:44:24 -07005046bool ClassLinker::LinkFields(Thread* self, ConstHandle<mirror::Class> klass, bool is_static,
5047 size_t* class_size) {
5048 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005049 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005050 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005051
Brian Carlstromea46f952013-07-30 01:26:50 -07005052 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005053 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005054
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005055 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005056 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005057 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005058 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
5059 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
5060 // Static fields come after the embedded tables.
5061 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
Fred Shih37f05ef2014-07-16 18:38:08 -07005062 0, 0, 0, 0, 0);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005063 }
5064 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005065 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005066 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005067 if (super_class != NULL) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005068 CHECK(super_class->IsResolved())
5069 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005070 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005071 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005072 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005073
Brian Carlstromf3632832014-05-20 15:36:53 -07005074 CHECK_EQ(num_fields == 0, fields == NULL) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005075
Brian Carlstromdbc05252011-09-09 01:59:59 -07005076 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005077 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005078 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Ian Rogers7b078e82014-09-10 14:44:24 -07005079 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005080 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005081 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005082 mirror::ArtField* f = fields->Get(i);
Brian Carlstromf3632832014-05-20 15:36:53 -07005083 CHECK(f != NULL) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005084 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005085 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005086 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5087 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005088
Fred Shih381e4ca2014-08-25 17:24:27 -07005089 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005090 size_t current_field = 0;
5091 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005092 FieldGaps gaps;
5093
Brian Carlstromdbc05252011-09-09 01:59:59 -07005094 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005095 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005096 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005097 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005098 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005099 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005100 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005101 if (UNLIKELY(!IsAligned<4>(field_offset.Uint32Value()))) {
5102 MemberOffset old_offset = field_offset;
5103 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5104 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5105 }
5106 DCHECK(IsAligned<4>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005107 grouped_and_sorted_fields.pop_front();
5108 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005109 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005110 field->SetOffset(field_offset);
5111 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005112 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005113 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5114 // otherwise we could end up with suboptimal gap fills.
5115 ShuffleForward<8>(num_fields, &current_field, &field_offset,
5116 fields, &grouped_and_sorted_fields, &gaps);
5117 ShuffleForward<4>(num_fields, &current_field, &field_offset,
5118 fields, &grouped_and_sorted_fields, &gaps);
5119 ShuffleForward<2>(num_fields, &current_field, &field_offset,
5120 fields, &grouped_and_sorted_fields, &gaps);
5121 ShuffleForward<1>(num_fields, &current_field, &field_offset,
5122 fields, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005123 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5124 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005125 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005126
Elliott Hughesadb460d2011-10-05 17:02:34 -07005127 // 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 -07005128 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005129 // We know there are no non-reference fields in the Reference classes, and we know
5130 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005131 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005132 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005133 --num_reference_fields;
5134 }
5135
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005136 if (kIsDebugBuild) {
5137 // Make sure that all reference fields appear before
5138 // non-reference fields, and all double-wide fields are aligned.
5139 bool seen_non_ref = false;
5140 for (size_t i = 0; i < num_fields; i++) {
5141 mirror::ArtField* field = fields->Get(i);
5142 if (false) { // enable to debug field layout
5143 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005144 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005145 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07005146 << " offset="
5147 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005148 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005149 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005150 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005151 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005152 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005153 is_primitive = true; // We lied above, so we have to expect a lie here.
5154 }
5155 if (is_primitive) {
5156 if (!seen_non_ref) {
5157 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07005158 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005159 }
5160 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07005161 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005162 }
5163 }
5164 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005165 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005166 }
5167 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005168
5169 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005170 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005171 if (is_static) {
5172 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005173 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005174 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005175 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005176 if (!klass->IsVariableSize()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005177 std::string temp;
5178 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005179 size_t previous_size = klass->GetObjectSize();
5180 if (previous_size != 0) {
5181 // Make sure that we didn't originally have an incorrect size.
Ian Rogers1ff3c982014-08-12 02:30:58 -07005182 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005183 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005184 klass->SetObjectSize(size);
5185 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005186 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005187 return true;
5188}
5189
5190// Set the bitmap of reference offsets, refOffsets, from the ifields
5191// list.
Mathieu Chartierbf99f772014-08-23 16:37:27 -07005192void ClassLinker::CreateReferenceInstanceOffsets(ConstHandle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005193 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005194 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005195 if (super_class != NULL) {
5196 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07005197 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005198 if (reference_offsets == CLASS_WALK_SUPER) {
5199 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005200 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005201 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005202 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005203 CreateReferenceOffsets(klass, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005204}
5205
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005206void ClassLinker::CreateReferenceOffsets(ConstHandle<mirror::Class> klass,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005207 uint32_t reference_offsets) {
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005208 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
5209 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07005210 // All of the fields that contain object references are guaranteed
5211 // to be at the beginning of the fields list.
5212 for (size_t i = 0; i < num_reference_fields; ++i) {
5213 // Note that byte_offset is the offset from the beginning of
5214 // object, not the offset into instance data
Ian Rogersef7d42f2014-01-06 12:55:46 -08005215 mirror::ArtField* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005216 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005217 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
5218 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
5219 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07005220 CHECK_NE(new_bit, 0U);
5221 reference_offsets |= new_bit;
5222 } else {
5223 reference_offsets = CLASS_WALK_SUPER;
5224 break;
5225 }
5226 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005227 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005228}
5229
Mathieu Chartier590fee92013-09-13 13:46:47 -07005230mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07005231 ConstHandle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005232 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005233 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005234 if (resolved != NULL) {
5235 return resolved;
5236 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005237 uint32_t utf16_length;
5238 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005239 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005240 dex_cache->SetResolvedString(string_idx, string);
5241 return string;
5242}
5243
Mathieu Chartier590fee92013-09-13 13:46:47 -07005244mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005245 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005246 StackHandleScope<2> hs(Thread::Current());
5247 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5248 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005249 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5250}
5251
5252mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07005253 ConstHandle<mirror::DexCache> dex_cache,
5254 ConstHandle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005255 DCHECK(dex_cache.Get() != NULL);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005256 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005257 if (resolved == NULL) {
Ian Rogers98379392014-02-24 16:53:16 -08005258 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005259 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005260 resolved = FindClass(self, descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005261 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005262 // TODO: we used to throw here if resolved's class loader was not the
5263 // boot class loader. This was to permit different classes with the
5264 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005265 dex_cache->SetResolvedType(type_idx, resolved);
5266 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005267 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005268 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005269 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005270 StackHandleScope<1> hs(self);
5271 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005272 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005273 DCHECK(resolved == NULL); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005274 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005275 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005276 self->GetException(NULL)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005277 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005278 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005279 }
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005280 DCHECK((resolved == NULL) || resolved->IsResolved() || resolved->IsErroneous())
5281 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005282 return resolved;
5283}
5284
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005285mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07005286 ConstHandle<mirror::DexCache> dex_cache,
5287 ConstHandle<mirror::ClassLoader> class_loader,
5288 ConstHandle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005289 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005290 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005291 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005292 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005293 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005294 return resolved;
5295 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005296 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005297 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005298 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005299 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005300 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005301 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005302 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005303 // Scan using method_idx, this saves string compares but will only hit for matching dex
5304 // caches/files.
5305 switch (type) {
5306 case kDirect: // Fall-through.
5307 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005308 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005309 break;
5310 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005311 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005312 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005313 break;
5314 case kSuper: // Fall-through.
5315 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005316 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005317 break;
5318 default:
5319 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005320 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005321 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005322 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005323 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005324 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005325 switch (type) {
5326 case kDirect: // Fall-through.
5327 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005328 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005329 break;
5330 case kInterface:
5331 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005332 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005333 break;
5334 case kSuper: // Fall-through.
5335 case kVirtual:
5336 resolved = klass->FindVirtualMethod(name, signature);
5337 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005338 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005339 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005340 // If we found a method, check for incompatible class changes.
5341 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005342 // Be a good citizen and update the dex cache to speed subsequent calls.
5343 dex_cache->SetResolvedMethod(method_idx, resolved);
5344 return resolved;
5345 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005346 // If we had a method, it's an incompatible-class-change error.
5347 if (resolved != nullptr) {
5348 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5349 } else {
5350 // We failed to find the method which means either an access error, an incompatible class
5351 // change, or no such method. First try to find the method among direct and virtual methods.
5352 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5353 const Signature signature = dex_file.GetMethodSignature(method_id);
5354 switch (type) {
5355 case kDirect:
5356 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005357 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005358 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5359 // have had a resolved method before, which triggers the "true" branch above.
5360 break;
5361 case kInterface:
5362 case kVirtual:
5363 case kSuper:
5364 resolved = klass->FindDirectMethod(name, signature);
5365 break;
5366 }
5367
5368 // If we found something, check that it can be accessed by the referrer.
5369 if (resolved != nullptr && referrer.Get() != nullptr) {
5370 mirror::Class* methods_class = resolved->GetDeclaringClass();
5371 mirror::Class* referring_class = referrer->GetDeclaringClass();
5372 if (!referring_class->CanAccess(methods_class)) {
5373 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5374 resolved, type);
5375 return nullptr;
5376 } else if (!referring_class->CanAccessMember(methods_class,
5377 resolved->GetAccessFlags())) {
5378 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5379 return nullptr;
5380 }
5381 }
5382
5383 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5384 // methods and throw if we find the method there. If we find nothing, throw a
5385 // NoSuchMethodError.
5386 switch (type) {
5387 case kDirect:
5388 case kStatic:
5389 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005390 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005391 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005392 resolved = klass->FindInterfaceMethod(name, signature);
5393 if (resolved != nullptr) {
5394 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5395 } else {
5396 ThrowNoSuchMethodError(type, klass, name, signature);
5397 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005398 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005399 break;
5400 case kInterface:
5401 if (resolved != nullptr) {
5402 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005403 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005404 resolved = klass->FindVirtualMethod(name, signature);
5405 if (resolved != nullptr) {
5406 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5407 } else {
5408 ThrowNoSuchMethodError(type, klass, name, signature);
5409 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005410 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005411 break;
5412 case kSuper:
Andreas Gampedf733752014-08-25 20:55:01 -07005413 if (resolved != nullptr) {
5414 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5415 } else {
5416 ThrowNoSuchMethodError(type, klass, name, signature);
5417 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005418 break;
5419 case kVirtual:
5420 if (resolved != nullptr) {
5421 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5422 } else {
5423 resolved = klass->FindInterfaceMethod(name, signature);
5424 if (resolved != nullptr) {
5425 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5426 } else {
5427 ThrowNoSuchMethodError(type, klass, name, signature);
5428 }
5429 }
5430 break;
5431 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005432 }
5433 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005434 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005435 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005436}
5437
Mathieu Chartier590fee92013-09-13 13:46:47 -07005438mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07005439 ConstHandle<mirror::DexCache> dex_cache,
5440 ConstHandle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005441 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005442 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005443 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005444 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005445 return resolved;
5446 }
5447 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005448 Thread* const self = Thread::Current();
5449 StackHandleScope<1> hs(self);
5450 Handle<mirror::Class> klass(
5451 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005452 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005453 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005454 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005455 }
5456
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005457 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005458 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005459 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005460 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005461 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005462
Andreas Gampe58a5af82014-07-31 16:23:49 -07005463 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005464 const char* name = dex_file.GetFieldName(field_id);
5465 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5466 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005467 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005468 } else {
5469 resolved = klass->FindInstanceField(name, type);
5470 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005471 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005472 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005473 return NULL;
5474 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005475 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005476 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005477 return resolved;
5478}
5479
Brian Carlstromea46f952013-07-30 01:26:50 -07005480mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005481 uint32_t field_idx,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07005482 ConstHandle<mirror::DexCache> dex_cache,
5483 ConstHandle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005484 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005485 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005486 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005487 return resolved;
5488 }
5489 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005490 Thread* self = Thread::Current();
5491 StackHandleScope<1> hs(self);
5492 Handle<mirror::Class> klass(
5493 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
5494 if (klass.Get() == NULL) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005495 DCHECK(Thread::Current()->IsExceptionPending());
5496 return NULL;
5497 }
5498
Ian Rogersdfb325e2013-10-30 01:00:44 -07005499 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5500 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005501 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005502 resolved = mirror::Class::FindField(self, klass, name, type);
Ian Rogersb067ac22011-12-13 18:05:09 -08005503 if (resolved != NULL) {
5504 dex_cache->SetResolvedField(field_idx, resolved);
5505 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005506 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005507 }
5508 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005509}
5510
Brian Carlstromea46f952013-07-30 01:26:50 -07005511const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005512 uint32_t* length) {
5513 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5514 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005515 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005516 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005517 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005518}
5519
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005520void ClassLinker::DumpAllClasses(int flags) {
5521 if (dex_cache_image_class_lookup_required_) {
5522 MoveImageClassesToClassTable();
5523 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005524 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5525 // 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 -08005526 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005527 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005528 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005529 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5530 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005531 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005532 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005533 }
5534
5535 for (size_t i = 0; i < all_classes.size(); ++i) {
5536 all_classes[i]->DumpClass(std::cerr, flags);
5537 }
5538}
5539
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005540void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005541 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005542 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005543 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005544 MoveImageClassesToClassTable();
5545 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005546 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005547 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005548}
5549
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005550size_t ClassLinker::NumLoadedClasses() {
5551 if (dex_cache_image_class_lookup_required_) {
5552 MoveImageClassesToClassTable();
5553 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005554 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005555 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005556}
5557
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005558pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005559 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005560}
5561
5562pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005563 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005564}
5565
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005566void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005567 DCHECK(!init_done_);
5568
5569 DCHECK(klass != NULL);
5570 DCHECK(klass->GetClassLoader() == NULL);
5571
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005572 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005573 DCHECK(class_roots != NULL);
5574 DCHECK(class_roots->Get(class_root) == NULL);
5575 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005576}
5577
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005578} // namespace art