blob: f927720ce4d1c5e814cf014e1f51f5999764d775 [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());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700123 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700124
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();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700132 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
133 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700134 }
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700135}
136
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800137static size_t Hash(const char* s) {
138 // This is the java.lang.String hashcode for convenience, not interoperability.
139 size_t hash = 0;
140 for (; *s != '\0'; ++s) {
141 hash = hash * 31 + *s;
142 }
143 return hash;
144}
145
Fred Shih381e4ca2014-08-25 17:24:27 -0700146// Gap between two fields in object layout.
147struct FieldGap {
148 uint32_t start_offset; // The offset from the start of the object.
149 uint32_t size; // The gap size of 1, 2, or 4 bytes.
150};
151struct FieldGapsComparator {
152 explicit FieldGapsComparator() {
153 }
154 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
155 NO_THREAD_SAFETY_ANALYSIS {
156 // Sort by gap size, largest first.
157 return lhs.size > rhs.size;
158 }
159};
160typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
161
162// Adds largest aligned gaps to queue of gaps.
163void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
164 DCHECK(gaps != nullptr);
165
166 uint32_t current_offset = gap_start;
167 while (current_offset != gap_end) {
168 size_t remaining = gap_end - current_offset;
169 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
170 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
171 current_offset += sizeof(uint32_t);
172 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
173 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
174 current_offset += sizeof(uint16_t);
175 } else {
176 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
177 current_offset += sizeof(uint8_t);
178 }
179 DCHECK_LE(current_offset, gap_end) << "Overran gap";
180 }
181}
182// Shuffle fields forward, making use of gaps whenever possible.
183template<int n>
184static void ShuffleForward(const size_t num_fields, size_t* current_field_idx,
185 MemberOffset* field_offset,
186 mirror::ObjectArray<mirror::ArtField>* fields,
187 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
188 FieldGaps* gaps)
189 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
190 DCHECK(current_field_idx != nullptr);
191 DCHECK(grouped_and_sorted_fields != nullptr);
192 DCHECK(fields != nullptr || (num_fields == 0 && grouped_and_sorted_fields->empty()));
193 DCHECK(gaps != nullptr);
194 DCHECK(field_offset != nullptr);
195
196 DCHECK(IsPowerOfTwo(n));
197 while (!grouped_and_sorted_fields->empty()) {
198 mirror::ArtField* field = grouped_and_sorted_fields->front();
199 Primitive::Type type = field->GetTypeAsPrimitiveType();
200 if (Primitive::ComponentSize(type) < n) {
201 break;
202 }
203 if (!IsAligned<n>(field_offset->Uint32Value())) {
204 MemberOffset old_offset = *field_offset;
205 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
206 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
207 }
208 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
209 grouped_and_sorted_fields->pop_front();
210 fields->Set<false>(*current_field_idx, field);
211 if (!gaps->empty() && gaps->top().size >= n) {
212 FieldGap gap = gaps->top();
213 gaps->pop();
214 DCHECK(IsAligned<n>(gap.start_offset));
215 field->SetOffset(MemberOffset(gap.start_offset));
216 if (gap.size > n) {
217 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
218 }
219 } else {
220 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
221 field->SetOffset(*field_offset);
222 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
223 }
224 ++(*current_field_idx);
225 }
226}
227
Elliott Hughes418d20f2011-09-22 14:00:39 -0700228const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700229 "Ljava/lang/Class;",
230 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700231 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700232 "[Ljava/lang/Object;",
233 "Ljava/lang/String;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700234 "Ljava/lang/DexCache;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700235 "Ljava/lang/ref/Reference;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700236 "Ljava/lang/reflect/ArtField;",
237 "Ljava/lang/reflect/ArtMethod;",
Ian Rogers466bb252011-10-14 03:29:56 -0700238 "Ljava/lang/reflect/Proxy;",
Mathieu Chartier66f19252012-09-18 08:57:04 -0700239 "[Ljava/lang/String;",
Brian Carlstromea46f952013-07-30 01:26:50 -0700240 "[Ljava/lang/reflect/ArtField;",
241 "[Ljava/lang/reflect/ArtMethod;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700242 "Ljava/lang/ClassLoader;",
Ian Rogers5167c972012-02-03 10:41:20 -0800243 "Ljava/lang/Throwable;",
jeffhao8cd6dda2012-02-22 10:15:34 -0800244 "Ljava/lang/ClassNotFoundException;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700245 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700246 "Z",
247 "B",
248 "C",
249 "D",
250 "F",
251 "I",
252 "J",
253 "S",
254 "V",
255 "[Z",
256 "[B",
257 "[C",
258 "[D",
259 "[F",
260 "[I",
261 "[J",
262 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700263 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700264};
265
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800266ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700267 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700268 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700269 dex_cache_image_class_lookup_required_(false),
270 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800271 class_roots_(nullptr),
272 array_iftable_(nullptr),
273 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700274 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800275 log_new_dex_caches_roots_(false),
276 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700277 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800278 portable_resolution_trampoline_(nullptr),
279 quick_resolution_trampoline_(nullptr),
280 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800281 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100282 quick_generic_jni_trampoline_(nullptr),
283 quick_to_interpreter_bridge_trampoline_(nullptr) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700284 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Ian Rogers98379392014-02-24 16:53:16 -0800285 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700286}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700287
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700288// To set a value for generic JNI. May be necessary in compiler tests.
289extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*);
Alex Light64ad14d2014-08-19 14:23:13 -0700290extern "C" void art_quick_resolution_trampoline(mirror::ArtMethod*);
291extern "C" void art_quick_imt_conflict_trampoline(mirror::ArtMethod*);
292extern "C" void art_quick_to_interpreter_bridge(mirror::ArtMethod*);
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700293
Alex Light64ad14d2014-08-19 14:23:13 -0700294void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800295 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700296 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700297
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700298 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700299
Elliott Hughes30646832011-10-13 16:59:46 -0700300 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700301 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700302 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700303 // 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 -0800304 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700305 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
306 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700307 heap->AllocNonMovableObject<true>(self, nullptr,
308 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700309 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700310 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700311 mirror::Class::SetClassClass(java_lang_Class.Get());
312 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700313 if (kUseBakerOrBrooksReadBarrier) {
314 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800315 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700316 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800317 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800318 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700319
Elliott Hughes418d20f2011-09-22 14:00:39 -0700320 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700321 Handle<mirror::Class> class_array_class(hs.NewHandle(
322 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700323 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700324
Ian Rogers23435d02012-09-24 11:23:12 -0700325 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700326 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
327 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700328 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700329 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700330 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700331 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700332
Ian Rogers23435d02012-09-24 11:23:12 -0700333 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700334 Handle<mirror::Class> object_array_class(hs.NewHandle(
335 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700336 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700337
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700338 // Setup the char (primitive) class to be used for char[].
339 Handle<mirror::Class> char_class(hs.NewHandle(
340 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700341
Ian Rogers23435d02012-09-24 11:23:12 -0700342 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700343 Handle<mirror::Class> char_array_class(hs.NewHandle(
344 AllocClass(self, java_lang_Class.Get(),
345 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700346 char_array_class->SetComponentType(char_class.Get());
347 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700348
Ian Rogers23435d02012-09-24 11:23:12 -0700349 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700350 Handle<mirror::Class> java_lang_String(hs.NewHandle(
351 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700352 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700353 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700354 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400355
Fred Shih4ee7a662014-07-11 09:59:27 -0700356 // Setup Reference.
357 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
358 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
359 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
360 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
361 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
362
Ian Rogers23435d02012-09-24 11:23:12 -0700363 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700364 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
365 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
366 kClassRootsMax));
367 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700368 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
369 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
370 SetClassRoot(kClassArrayClass, class_array_class.Get());
371 SetClassRoot(kObjectArrayClass, object_array_class.Get());
372 SetClassRoot(kCharArrayClass, char_array_class.Get());
373 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700374 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700375
376 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700377 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
378 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
379 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
380 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
381 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
382 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
383 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
384 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700385
Ian Rogers23435d02012-09-24 11:23:12 -0700386 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700387 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700388
Ian Rogers23435d02012-09-24 11:23:12 -0700389 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700390 Handle<mirror::Class> int_array_class(hs.NewHandle(
391 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700393 mirror::IntArray::SetArrayClass(int_array_class.Get());
394 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700395
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700396 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700397
Ian Rogers52813c92012-10-11 11:50:38 -0700398 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700399 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
400 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700401 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700402 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700403 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700404
Brian Carlstromf3632832014-05-20 15:36:53 -0700405 // Constructor, Field, Method, and AbstractMethod are necessary so
406 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700407 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
408 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700409 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700410 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700411 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700412 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700413 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700415 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
416 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700417 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700418 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700419 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700420 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700421
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700422 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700423
424 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700425 Handle<mirror::Class> object_array_string(hs.NewHandle(
426 AllocClass(self, java_lang_Class.Get(),
427 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700428 object_array_string->SetComponentType(java_lang_String.Get());
429 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700430
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700431 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
432 AllocClass(self, java_lang_Class.Get(),
433 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700434 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
435 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700436
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700437 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
438 AllocClass(self, java_lang_Class.Get(),
439 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700440 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
441 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700442
Ian Rogers23435d02012-09-24 11:23:12 -0700443 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
444 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
445 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700446 CHECK_NE(0U, boot_class_path.size());
447 for (size_t i = 0; i != boot_class_path.size(); ++i) {
448 const DexFile* dex_file = boot_class_path[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700449 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700450 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700451 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700452
453 // now we can use FindSystemClass
454
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700455 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700456 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
457 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700458
Jeff Hao88474b42013-10-23 16:24:40 -0700459 // Create runtime resolution and imt conflict methods. Also setup the default imt.
460 Runtime* runtime = Runtime::Current();
461 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
462 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
463 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
464
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700465 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
466 // we do not need friend classes or a publicly exposed setter.
467 quick_generic_jni_trampoline_ = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
Alex Light64ad14d2014-08-19 14:23:13 -0700468 if (!runtime->IsCompiler()) {
469 // We need to set up the generic trampolines since we don't have an image.
470 quick_resolution_trampoline_ = reinterpret_cast<void*>(art_quick_resolution_trampoline);
471 quick_imt_conflict_trampoline_ = reinterpret_cast<void*>(art_quick_imt_conflict_trampoline);
472 quick_to_interpreter_bridge_trampoline_ = reinterpret_cast<void*>(art_quick_to_interpreter_bridge);
473 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700474
Mathieu Chartier66f19252012-09-18 08:57:04 -0700475 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700476 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800477 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700478 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700479 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700480 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800481 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700482 std::ostringstream os1, os2;
483 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
484 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
485 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
486 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700487 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800488 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700489 CHECK_EQ(java_lang_String.Get(), String_class);
490 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700491 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700492
Ian Rogers23435d02012-09-24 11:23:12 -0700493 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800494 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800495 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700496
Ian Rogers98379392014-02-24 16:53:16 -0800497 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800498 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700499
Ian Rogers98379392014-02-24 16:53:16 -0800500 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700501 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700502
Ian Rogers98379392014-02-24 16:53:16 -0800503 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800504 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700505
Ian Rogers98379392014-02-24 16:53:16 -0800506 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700507 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700508
Ian Rogers98379392014-02-24 16:53:16 -0800509 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800510 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700511
Ian Rogers98379392014-02-24 16:53:16 -0800512 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800513 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700514
Ian Rogers98379392014-02-24 16:53:16 -0800515 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800516 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700517
Ian Rogers98379392014-02-24 16:53:16 -0800518 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700519 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700520
Ian Rogers98379392014-02-24 16:53:16 -0800521 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700522 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700523
Ian Rogers23435d02012-09-24 11:23:12 -0700524 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800525 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700526 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800527 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700528 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700529 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
530 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700531 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700532 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700533 array_iftable->SetInterface(0, java_lang_Cloneable);
534 array_iftable->SetInterface(1, java_io_Serializable);
535 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700536
Ian Rogers23435d02012-09-24 11:23:12 -0700537 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700538 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
539 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
540 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
541 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700542 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700543 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800544 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700545 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700546
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700547 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800548 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700549 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700550
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700551 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800552 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700553 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554
Brian Carlstromf3632832014-05-20 15:36:53 -0700555 mirror::Class* String_array_class =
556 FindSystemClass(self, class_roots_descriptors_[kJavaLangStringArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700557 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700558
Brian Carlstromea46f952013-07-30 01:26:50 -0700559 mirror::Class* Art_method_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800560 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700561 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700562
Brian Carlstromea46f952013-07-30 01:26:50 -0700563 mirror::Class* Art_field_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800564 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700565 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700566
Ian Rogers23435d02012-09-24 11:23:12 -0700567 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700568
Ian Rogers23435d02012-09-24 11:23:12 -0700569 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800570 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700571 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
572
Brian Carlstrom1f870082011-08-23 16:02:11 -0700573 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700574 // finish initializing Reference class
575 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
576 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
577 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
578 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
579 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700580 mirror::Class* java_lang_ref_FinalizerReference =
581 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700582 java_lang_ref_FinalizerReference->SetAccessFlags(
583 java_lang_ref_FinalizerReference->GetAccessFlags() |
584 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700585 mirror::Class* java_lang_ref_PhantomReference =
586 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700587 java_lang_ref_PhantomReference->SetAccessFlags(
588 java_lang_ref_PhantomReference->GetAccessFlags() |
589 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700590 mirror::Class* java_lang_ref_SoftReference =
591 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700592 java_lang_ref_SoftReference->SetAccessFlags(
593 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700594 mirror::Class* java_lang_ref_WeakReference =
595 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700596 java_lang_ref_WeakReference->SetAccessFlags(
597 java_lang_ref_WeakReference->GetAccessFlags() |
598 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700599
Ian Rogers23435d02012-09-24 11:23:12 -0700600 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800601 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700602 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700603 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
604
jeffhao8cd6dda2012-02-22 10:15:34 -0800605 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700606 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800607 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800608 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700609 SetClassRoot(kJavaLangClassNotFoundException,
610 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800611 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700612 SetClassRoot(kJavaLangStackTraceElementArrayClass,
613 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800614 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700615
Ian Rogers98379392014-02-24 16:53:16 -0800616 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700617
Brian Carlstroma004aa92012-02-08 18:05:09 -0800618 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700619}
620
Ian Rogers98379392014-02-24 16:53:16 -0800621void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800622 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700623
624 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700625 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700626 // as the types of the field can't be resolved prior to the runtime being
627 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800628 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700629 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800630 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800631
Brian Carlstromea46f952013-07-30 01:26:50 -0700632 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700633 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
634 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700635
Brian Carlstromea46f952013-07-30 01:26:50 -0700636 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700637 CHECK_STREQ(queue->GetName(), "queue");
638 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700639
Brian Carlstromea46f952013-07-30 01:26:50 -0700640 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700641 CHECK_STREQ(queueNext->GetName(), "queueNext");
642 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700643
Brian Carlstromea46f952013-07-30 01:26:50 -0700644 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700645 CHECK_STREQ(referent->GetName(), "referent");
646 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700647
Brian Carlstromea46f952013-07-30 01:26:50 -0700648 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700649 CHECK_STREQ(zombie->GetName(), "zombie");
650 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700651
Brian Carlstroma663ea52011-08-19 23:33:41 -0700652 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700653 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700654 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800655 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700656 CHECK(klass != nullptr);
657 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700658 // note SetClassRoot does additional validation.
659 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700660 }
661
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700662 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700663
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700664 // disable the slow paths in FindClass and CreatePrimitiveClass now
665 // that Object, Class, and Object[] are setup
666 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700667
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800668 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700669}
670
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700671void ClassLinker::RunRootClinits() {
672 Thread* self = Thread::Current();
673 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800674 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700675 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700676 StackHandleScope<1> hs(self);
677 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700678 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700679 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700680 }
681 }
682}
683
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700684bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800685 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000686 const char* oat_cache_filename,
687 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700688 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700689 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800690
Ian Rogers1d54e732013-05-02 21:10:01 -0700691 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800692 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700693 if (heap->GetImageSpace() == nullptr) {
694 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
695 // out of space anyway it might not matter.
696 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
697 "without an image.", dex_filename);
698 return false;
699 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700700 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800701
Brian Carlstrom6449c622014-02-10 23:48:36 -0800702 std::string dex_file_option("--dex-file=");
703 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800704
Brian Carlstrom6449c622014-02-10 23:48:36 -0800705 std::string oat_fd_option("--oat-fd=");
706 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800707
Brian Carlstrom6449c622014-02-10 23:48:36 -0800708 std::string oat_location_option("--oat-location=");
709 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800710
Brian Carlstrom6449c622014-02-10 23:48:36 -0800711 std::vector<std::string> argv;
712 argv.push_back(dex2oat);
713 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800714 argv.push_back("-classpath");
715 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800716 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800717
Ian Rogers8afeb852014-04-02 14:55:49 -0700718 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800719
Jeff Hao4a200f52014-04-01 14:58:49 -0700720 if (!Runtime::Current()->IsVerificationEnabled()) {
721 argv.push_back("--compiler-filter=verify-none");
722 }
723
Alex Light6e183f22014-07-18 14:57:04 -0700724 if (Runtime::Current()->MustRelocateIfPossible()) {
725 argv.push_back("--runtime-arg");
726 argv.push_back("-Xrelocate");
727 } else {
728 argv.push_back("--runtime-arg");
729 argv.push_back("-Xnorelocate");
730 }
731
Brian Carlstrom6449c622014-02-10 23:48:36 -0800732 if (!kIsTargetBuild) {
733 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700734 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700735
Brian Carlstrom6449c622014-02-10 23:48:36 -0800736 argv.push_back(boot_image_option);
737 argv.push_back(dex_file_option);
738 argv.push_back(oat_fd_option);
739 argv.push_back(oat_location_option);
740 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800741 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800742 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700743 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800744
745 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700746}
747
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700748const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700749 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800750 if (kIsDebugBuild) {
751 for (size_t i = 0; i < oat_files_.size(); ++i) {
752 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700753 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800754 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700755 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
756 oat_files_.push_back(oat_file);
757 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800758}
759
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700760OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
761 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700762 OatFile* oat_file = space->ReleaseOatFile();
763 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700764 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700765 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700766}
767
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100768const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800769 const char* dex_location = dex_file.GetLocation().c_str();
770 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100771 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800772}
773
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100774const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
775 const char* dex_location,
776 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700777 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100778 for (const OatFile* oat_file : oat_files_) {
779 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700780
781 if (oat_location != nullptr) {
782 if (oat_file->GetLocation() != oat_location) {
783 continue;
784 }
785 }
786
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700787 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800788 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700789 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100790 if (oat_dex_file != nullptr) {
791 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800792 }
793 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100794 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800795}
796
Calin Juravle621962a2014-09-02 15:53:55 +0100797
798// Loads all multi dex files from the given oat file returning true on success.
799//
800// Parameters:
801// oat_file - the oat file to load from
802// dex_location - the dex location used to generate the oat file
803// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
804// generated - whether or not the oat_file existed before or was just (re)generated
805// error_msgs - any error messages will be appended here
806// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
807static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
808 const char* dex_location,
809 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700810 bool generated,
811 std::vector<std::string>* error_msgs,
812 std::vector<const DexFile*>* dex_files) {
813 if (oat_file == nullptr) {
814 return false;
815 }
816
817 size_t old_size = dex_files->size(); // To rollback on error.
818
819 bool success = true;
820 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100821 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700822 const char* next_name = next_name_str.c_str();
823
Calin Juravle621962a2014-09-02 15:53:55 +0100824 uint32_t next_location_checksum;
825 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700826 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100827 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
828 // When i=0 the multidex name should be the same as the location name. We already have the
829 // checksum it so we don't need to recompute it.
830 if (dex_location_checksum == nullptr) {
831 next_location_checksum_pointer = nullptr;
832 } else {
833 next_location_checksum = *dex_location_checksum;
834 }
835 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700836 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100837 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700838 }
839
840 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
841
842 if (oat_dex_file == nullptr) {
843 if (i == 0 && generated) {
844 std::string error_msg;
845 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100846 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700847 oat_file->GetLocation().c_str());
848 error_msgs->push_back(error_msg);
849 }
850 break; // Not found, done.
851 }
852
853 // Checksum test. Test must succeed when generated.
854 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100855 if (next_location_checksum_pointer != nullptr) {
856 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700857 }
858
859 if (success) {
860 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
861 if (dex_file == nullptr) {
862 success = false;
863 error_msgs->push_back(error_msg);
864 } else {
865 dex_files->push_back(dex_file);
866 }
867 }
868
869 // When we generated the file, we expect success, or something is terribly wrong.
870 CHECK_EQ(false, generated && !success)
871 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100872 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700873 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
874 }
875
876 if (dex_files->size() == old_size) {
877 success = false; // We did not even find classes.dex
878 }
879
880 if (success) {
881 return true;
882 } else {
883 // Free all the dex files we have loaded.
884 auto it = dex_files->begin() + old_size;
885 auto it_end = dex_files->end();
886 for (; it != it_end; it++) {
887 delete *it;
888 }
889 dex_files->erase(dex_files->begin() + old_size, it_end);
890
891 return false;
892 }
893}
894
895// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
896// complicates the loading process, as we should not use an iterative loading process, because that
897// would register the oat file and dex files that come before the broken one. Instead, check all
898// multidex ahead of time.
899bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
900 std::vector<std::string>* error_msgs,
901 std::vector<const DexFile*>* dex_files) {
902 // 1) Check whether we have an open oat file.
903 // This requires a dex checksum, use the "primary" one.
904 uint32_t dex_location_checksum;
905 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
906 bool have_checksum = true;
907 std::string checksum_error_msg;
908 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100909 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700910 dex_location_checksum_pointer = nullptr;
911 have_checksum = false;
912 }
913
914 bool needs_registering = false;
915
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100916 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
917 dex_location_checksum_pointer);
918 std::unique_ptr<const OatFile> open_oat_file(
919 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700920
921 // 2) If we do not have an open one, maybe there's one on disk already.
922
923 // In case the oat file is not open, we play a locking game here so
924 // that if two different processes race to load and register or generate
925 // (or worse, one tries to open a partial generated file) we will be okay.
926 // This is actually common with apps that use DexClassLoader to work
927 // around the dex method reference limit and that have a background
928 // service running in a separate process.
929 ScopedFlock scoped_flock;
930
931 if (open_oat_file.get() == nullptr) {
932 if (oat_location != nullptr) {
933 // Can only do this if we have a checksum, else error.
934 if (!have_checksum) {
935 error_msgs->push_back(checksum_error_msg);
936 return false;
937 }
938
939 std::string error_msg;
940
941 // We are loading or creating one in the future. Time to set up the file lock.
942 if (!scoped_flock.Init(oat_location, &error_msg)) {
943 error_msgs->push_back(error_msg);
944 return false;
945 }
946
Alex Lighta59dd802014-07-02 16:28:08 -0700947 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700948 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
949 oat_location, &error_msg));
950
951 if (open_oat_file.get() == nullptr) {
952 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
953 dex_location, oat_location, error_msg.c_str());
954 VLOG(class_linker) << compound_msg;
955 error_msgs->push_back(compound_msg);
956 }
957 } else {
958 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100959 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700960 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
961 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100962 kRuntimeISA, error_msgs,
963 &obsolete_file_cleanup_failed));
964 // There's no point in going forward and eventually try to regenerate the
965 // file if we couldn't remove the obsolete one. Mostly likely we will fail
966 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100967 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
968 if (obsolete_file_cleanup_failed) {
969 return false;
970 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700971 }
972 needs_registering = true;
973 }
974
975 // 3) If we have an oat file, check all contained multidex files for our dex_location.
976 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100977 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
978 dex_location_checksum_pointer,
979 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700980 if (success) {
981 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
982 if (needs_registering) {
983 // We opened the oat file, so we must register it.
984 RegisterOatFile(oat_file);
985 }
Alex Light9dcc4572014-08-14 14:16:26 -0700986 // If the file isn't executable we failed patchoat but did manage to get the dex files.
987 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700988 } else {
989 if (needs_registering) {
990 // We opened it, delete it.
991 open_oat_file.reset();
992 } else {
993 open_oat_file.release(); // Do not delete open oat files.
994 }
995 }
996
997 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
998
999 // Need a checksum, fail else.
1000 if (!have_checksum) {
1001 error_msgs->push_back(checksum_error_msg);
1002 return false;
1003 }
1004
1005 // Look in cache location if no oat_location is given.
1006 std::string cache_location;
1007 if (oat_location == nullptr) {
1008 // Use the dalvik cache.
1009 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
1010 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
1011 oat_location = cache_location.c_str();
1012 }
1013
Alex Light64ad14d2014-08-19 14:23:13 -07001014 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -07001015 // Definitely need to lock now.
1016 if (!scoped_flock.HasFile()) {
1017 std::string error_msg;
1018 if (!scoped_flock.Init(oat_location, &error_msg)) {
1019 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -07001020 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -07001021 }
1022 }
1023
Alex Light64ad14d2014-08-19 14:23:13 -07001024 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001025 // Create the oat file.
1026 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1027 oat_location, error_msgs));
1028 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001029
1030 // Failed, bail.
1031 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001032 std::string error_msg;
1033 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1034 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1035 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001036 return false;
1037 }
1038
1039 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001040 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1041 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001042 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001043 if (success) {
1044 RegisterOatFile(open_oat_file.release());
1045 return true;
1046 } else {
1047 return false;
1048 }
1049}
1050
1051const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1052 uint32_t dex_location_checksum,
1053 const char* oat_location,
1054 std::string* error_msg) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001055 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001056 !Runtime::Current()->IsCompiler(),
1057 error_msg));
1058 if (oat_file.get() == nullptr) {
1059 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1060 error_msg->c_str());
1061 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001062 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001063 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001064 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1065 if (image_space != nullptr) {
1066 const ImageHeader& image_header = image_space->GetImageHeader();
1067 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1068 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1069 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1070 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1071 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1072 actual_image_oat_checksum);
1073 return nullptr;
1074 }
1075
1076 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1077 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1078 if (expected_image_oat_offset != actual_image_oat_offset) {
1079 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1080 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1081 actual_image_oat_offset);
1082 return nullptr;
1083 }
1084 int32_t expected_patch_delta = image_header.GetPatchDelta();
1085 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1086 if (expected_patch_delta != actual_patch_delta) {
1087 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1088 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1089 return nullptr;
1090 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001091 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001092
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001093 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1094 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001095 if (oat_dex_file == nullptr) {
1096 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1097 dex_location);
1098 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001099 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001100 uint32_t expected_dex_checksum = dex_location_checksum;
1101 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1102 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001103 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1104 "found 0x%x", oat_location, expected_dex_checksum,
1105 actual_dex_checksum);
1106 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001107 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001108 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1109 if (dex_file.get() != nullptr) {
1110 return oat_file.release();
1111 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001112 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001113 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001114}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001115
Andreas Gampe833a4852014-05-21 18:46:59 -07001116const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1117 int fd, const char* oat_location,
1118 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001119 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001120 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001121 std::string error_msg;
1122 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001123 CHECK(!error_msg.empty());
1124 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001125 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001126 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001127 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001128 !Runtime::Current()->IsCompiler(),
1129 &error_msg));
1130 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001131 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1132 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001133 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001134 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001135 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001136
1137 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001138}
1139
Alex Light6e183f22014-07-18 14:57:04 -07001140bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1141 const InstructionSet instruction_set) {
1142 Runtime* runtime = Runtime::Current();
1143 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001144 if (image_space == nullptr) {
1145 return false;
1146 }
Alex Light6e183f22014-07-18 14:57:04 -07001147 uint32_t image_oat_checksum = 0;
1148 if (instruction_set == kRuntimeISA) {
1149 const ImageHeader& image_header = image_space->GetImageHeader();
1150 image_oat_checksum = image_header.GetOatChecksum();
1151 } else {
1152 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1153 image_space->GetImageLocation().c_str(), instruction_set));
1154 image_oat_checksum = image_header->GetOatChecksum();
1155 }
1156 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1157}
1158
1159bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1160 const InstructionSet instruction_set,
1161 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001162 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001163 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001164 if (image_space == nullptr) {
1165 *error_msg = "No image space for verification against";
1166 return false;
1167 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001168
1169 // If the requested instruction set is the same as the current runtime,
1170 // we can use the checksums directly. If it isn't, we'll have to read the
1171 // image header from the image for the right instruction set.
1172 uint32_t image_oat_checksum = 0;
1173 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001174 int32_t image_patch_delta = 0;
1175 if (instruction_set == Runtime::Current()->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001176 const ImageHeader& image_header = image_space->GetImageHeader();
1177 image_oat_checksum = image_header.GetOatChecksum();
1178 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001179 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001180 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001181 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001182 image_space->GetImageLocation().c_str(), instruction_set));
1183 image_oat_checksum = image_header->GetOatChecksum();
1184 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001185 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001186 }
1187 const OatHeader& oat_header = oat_file->GetOatHeader();
Alex Light6e183f22014-07-18 14:57:04 -07001188 bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1189 && (oat_header.GetImagePatchDelta() == image_patch_delta)
1190 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1191 if (!ret) {
1192 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1193 oat_file->GetLocation().c_str(),
1194 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1195 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1196 oat_file->GetOatHeader().GetImagePatchDelta(),
1197 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1198 }
1199 return ret;
1200}
1201
1202bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1203 const char* dex_location,
1204 uint32_t dex_location_checksum,
1205 const InstructionSet instruction_set,
1206 std::string* error_msg) {
1207 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1208 return false;
1209 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001210
Brian Carlstromf3632832014-05-20 15:36:53 -07001211 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1212 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001213 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001214 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1215 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001216 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1217 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001218 oat_file->GetLocation().c_str(),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001219 oat_dex_file->GetDexFileLocation().c_str(),
1220 oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001221 }
1222 return false;
1223 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001224
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001225 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001226 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001227}
1228
Alex Lighta59dd802014-07-02 16:28:08 -07001229bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1230 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001231 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001232 std::string* error_msg) {
1233 CHECK(oat_file != nullptr);
1234 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001235 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001236 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001237 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1238 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1239 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001240 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001241 if (oat_dex_file == nullptr) {
1242 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001243 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001244 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001245 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001246 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001247 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001248 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001249 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001250 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001251 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001252 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001253 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001254 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001255 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001256 }
Alex Lighta59dd802014-07-02 16:28:08 -07001257 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001258}
1259
Andreas Gampe833a4852014-05-21 18:46:59 -07001260const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001261 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001262 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001263 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001264 std::vector<std::string>* error_msgs,
1265 bool* obsolete_file_cleanup_failed) {
1266 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001267 bool already_opened = false;
1268 std::string dex_location_str(dex_location);
1269 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1270 &already_opened,
1271 obsolete_file_cleanup_failed,
1272 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001273 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001274 if (oat_file.get() == nullptr) {
1275 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1276 dex_location));
1277 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001278 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001279 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1280 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001281 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1282 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001283 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001284 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001285 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001286 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001287 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1288 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1289 "dex location '%s'. Image checksum incorrect.",
1290 oat_file->GetLocation().c_str(), dex_location));
1291 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001292 } else {
1293 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001294 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001295}
1296
Brian Carlstromae826982011-11-09 01:33:42 -08001297const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001298 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001299 for (size_t i = 0; i < oat_files_.size(); i++) {
1300 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001301 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001302 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001303 return oat_file;
1304 }
1305 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001306 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001307}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001308
Alex Lighta59dd802014-07-02 16:28:08 -07001309const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1310 InstructionSet isa,
1311 bool *already_opened,
1312 bool *obsolete_file_cleanup_failed,
1313 std::vector<std::string>* error_msgs) {
1314 // Find out if we've already opened the file
1315 const OatFile* ret = nullptr;
1316 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1317 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1318 if (ret != nullptr) {
1319 *already_opened = true;
1320 return ret;
1321 }
1322
1323 std::string dalvik_cache;
1324 bool have_android_data = false;
1325 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001326 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001327 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001328 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001329 std::string cache_filename;
1330 if (have_dalvik_cache) {
1331 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1332 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1333 if (ret != nullptr) {
1334 *already_opened = true;
1335 return ret;
1336 }
1337 } else {
1338 // If we need to relocate we should just place odex back where it started.
1339 cache_filename = odex_filename;
1340 }
1341
1342 ret = nullptr;
1343
1344 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1345 //
1346 // Now we do the following:
1347 // 1) Try and open the odex version
1348 // 2) If present, checksum-verified & relocated correctly return it
1349 // 3) Close the odex version to free up its address space.
1350 // 4) Try and open the cache version
1351 // 5) If present, checksum-verified & relocated correctly return it
1352 // 6) Close the cache version to free up its address space.
1353 // 7) If we should relocate:
1354 // a) If we have opened and checksum-verified the odex version relocate it to
1355 // 'cache_filename' and return it
1356 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1357 // it. This should not happen often (I think only the run-test's will hit this case).
1358 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1359 // this point.
1360 // 9) Return nullptr
1361
1362 *already_opened = false;
1363 const Runtime* runtime = Runtime::Current();
1364 CHECK(runtime != nullptr);
1365 bool executable = !runtime->IsCompiler();
1366
1367 std::string odex_error_msg;
1368 bool should_patch_system = false;
1369 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001370 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001371 {
1372 // There is a high probability that these both these oat files map similar/the same address
1373 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001374 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001375 executable, &odex_error_msg));
1376 if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1377 &odex_checksum_verified,
1378 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001379 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001380 } else {
1381 if (odex_checksum_verified) {
1382 // We can just relocate
1383 should_patch_system = true;
1384 odex_error_msg = "Image Patches are incorrect";
1385 }
1386 if (odex_oat_file.get() != nullptr) {
1387 have_system_odex = true;
1388 }
Alex Lighta59dd802014-07-02 16:28:08 -07001389 }
1390 }
1391
Alex Lighta59dd802014-07-02 16:28:08 -07001392 std::string cache_error_msg;
1393 bool should_patch_cache = false;
1394 bool cache_checksum_verified = false;
1395 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001396 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001397 executable, &cache_error_msg));
1398 if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1399 &cache_checksum_verified,
1400 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001401 return cache_oat_file.release();
1402 } else if (cache_checksum_verified) {
1403 // We can just relocate
1404 should_patch_cache = true;
1405 cache_error_msg = "Image Patches are incorrect";
1406 }
1407 } else if (have_android_data) {
1408 // dalvik_cache does not exist but android data does. This means we should be able to create
1409 // it, so we should try.
1410 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1411 }
1412
1413 ret = nullptr;
1414 std::string error_msg;
1415 if (runtime->CanRelocate()) {
1416 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001417 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1418 if (space != nullptr) {
1419 const std::string& image_location = space->GetImageLocation();
1420 if (odex_checksum_verified && should_patch_system) {
1421 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1422 } else if (cache_checksum_verified && should_patch_cache) {
1423 CHECK(have_dalvik_cache);
1424 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1425 }
Alex Light84d76052014-08-22 17:49:35 -07001426 } else if (have_system_odex) {
1427 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001428 }
1429 }
1430 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1431 // implicitly: were able to fine where the cached version is but we were unable to use it,
1432 // either as a destination for relocation or to open a file. We should delete it if it is
1433 // there.
1434 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1435 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1436 "searching for dex file %s: %s",
1437 cache_filename.c_str(), dex_location.c_str(),
1438 strerror(errno));
1439 error_msgs->push_back(rm_error_msg);
1440 VLOG(class_linker) << rm_error_msg;
1441 // Let the caller know that we couldn't remove the obsolete file.
1442 // This is a good indication that further writes may fail as well.
1443 *obsolete_file_cleanup_failed = true;
1444 }
1445 }
1446 if (ret == nullptr) {
1447 VLOG(class_linker) << error_msg;
1448 error_msgs->push_back(error_msg);
1449 std::string relocation_msg;
1450 if (runtime->CanRelocate()) {
1451 relocation_msg = StringPrintf(" and relocation failed");
1452 }
1453 if (have_dalvik_cache && cache_checksum_verified) {
1454 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1455 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1456 cache_filename.c_str(), cache_error_msg.c_str(),
1457 relocation_msg.c_str());
1458 } else {
1459 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1460 "dalvik_cache availible)%s.", odex_filename.c_str(),
1461 odex_error_msg.c_str(), relocation_msg.c_str());
1462 }
1463 VLOG(class_linker) << error_msg;
1464 error_msgs->push_back(error_msg);
1465 }
1466 return ret;
1467}
1468
Alex Light9dcc4572014-08-14 14:16:26 -07001469const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1470 InstructionSet isa,
1471 std::string* error_msg) {
1472 // We open it non-executable
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001473 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001474 if (output.get() == nullptr) {
1475 return nullptr;
1476 }
Alex Light84d76052014-08-22 17:49:35 -07001477 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1478 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001479 return output.release();
1480 } else {
1481 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1482 oat_path.c_str());
1483 return nullptr;
1484 }
1485}
1486
Alex Lighta59dd802014-07-02 16:28:08 -07001487const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1488 const std::string& output_oat,
1489 const std::string& image_location,
1490 InstructionSet isa,
1491 std::string* error_msg) {
Alex Light64ad14d2014-08-19 14:23:13 -07001492 if (!Runtime::Current()->GetHeap()->HasImageSpace()) {
1493 // We don't have an image space so there is no point in trying to patchoat.
1494 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1495 << "running without an image. Attempting to use oat file for interpretation.";
1496 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1497 }
Alex Light9dcc4572014-08-14 14:16:26 -07001498 if (!Runtime::Current()->IsDex2OatEnabled()) {
1499 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1500 // input_oat but make sure we only do interpretation on it's dex files.
1501 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1502 << "disabled. Attempting to use oat file for interpretation";
1503 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1504 }
Alex Lighta59dd802014-07-02 16:28:08 -07001505 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
1506 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1507
1508 std::string isa_arg("--instruction-set=");
1509 isa_arg += GetInstructionSetString(isa);
1510 std::string input_oat_filename_arg("--input-oat-file=");
1511 input_oat_filename_arg += input_oat;
1512 std::string output_oat_filename_arg("--output-oat-file=");
1513 output_oat_filename_arg += output_oat;
1514 std::string patched_image_arg("--patched-image-location=");
1515 patched_image_arg += image_location;
1516
1517 std::vector<std::string> argv;
1518 argv.push_back(patchoat);
1519 argv.push_back(isa_arg);
1520 argv.push_back(input_oat_filename_arg);
1521 argv.push_back(output_oat_filename_arg);
1522 argv.push_back(patched_image_arg);
1523
1524 std::string command_line(Join(argv, ' '));
1525 LOG(INFO) << "Relocate Oat File: " << command_line;
1526 bool success = Exec(argv, error_msg);
1527 if (success) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001528 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001529 !Runtime::Current()->IsCompiler(), error_msg));
1530 bool checksum_verified = false;
1531 if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1532 return output.release();
1533 } else if (output.get() != nullptr) {
1534 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1535 "but output file '%s' failed verifcation: %s",
1536 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1537 } else {
1538 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1539 "but was unable to open output file '%s': %s",
1540 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1541 }
Alex Light9dcc4572014-08-14 14:16:26 -07001542 } else if (!Runtime::Current()->IsCompiler()) {
1543 // patchoat failed which means we probably don't have enough room to place the output oat file,
1544 // instead of failing we should just run the interpreter from the dex files in the input oat.
1545 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1546 << "for interpretation. patchoat failure was: " << *error_msg;
1547 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001548 } else {
1549 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1550 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1551 error_msg->c_str());
1552 }
1553 return nullptr;
1554}
1555
1556int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1557 Runtime* runtime = Runtime::Current();
1558 int32_t real_patch_delta;
1559 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001560 CHECK(image_space != nullptr);
Alex Lighta59dd802014-07-02 16:28:08 -07001561 if (isa == Runtime::Current()->GetInstructionSet()) {
1562 const ImageHeader& image_header = image_space->GetImageHeader();
1563 real_patch_delta = image_header.GetPatchDelta();
1564 } else {
1565 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1566 image_space->GetImageLocation().c_str(), isa));
1567 real_patch_delta = image_header->GetPatchDelta();
1568 }
1569 const OatHeader& oat_header = oat_file->GetOatHeader();
1570 return real_patch_delta - oat_header.GetImagePatchDelta();
1571}
1572
1573bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1574 bool* checksum_verified,
1575 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001576 Runtime* runtime = Runtime::Current();
Alex Lighta59dd802014-07-02 16:28:08 -07001577 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001578 if (image_space == nullptr) {
1579 *error_msg = "No image space present";
1580 return false;
1581 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001582 uint32_t real_image_checksum;
1583 void* real_image_oat_offset;
1584 int32_t real_patch_delta;
1585 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001586 const ImageHeader& image_header = image_space->GetImageHeader();
1587 real_image_checksum = image_header.GetOatChecksum();
1588 real_image_oat_offset = image_header.GetOatDataBegin();
1589 real_patch_delta = image_header.GetPatchDelta();
1590 } else {
1591 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1592 image_space->GetImageLocation().c_str(), isa));
1593 real_image_checksum = image_header->GetOatChecksum();
1594 real_image_oat_offset = image_header->GetOatDataBegin();
1595 real_patch_delta = image_header->GetPatchDelta();
1596 }
1597
1598 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001599 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001600
1601 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1602 *checksum_verified = oat_image_checksum == real_image_checksum;
1603 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001604 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1605 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001606 }
1607
1608 void* oat_image_oat_offset =
1609 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1610 bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1611 if (!offset_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001612 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1613 real_image_oat_offset, oat_image_oat_offset);
Alex Lighta59dd802014-07-02 16:28:08 -07001614 }
1615
1616 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1617 bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1618 if (!patch_delta_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001619 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, received 0x%x)",
1620 real_patch_delta, oat_patch_delta);
Alex Lighta59dd802014-07-02 16:28:08 -07001621 }
1622
1623 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001624 if (!ret) {
1625 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001626 }
1627 return ret;
1628}
1629
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001630const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1631 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001632 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001633 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001634 return oat_file;
1635 }
1636
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001637 return OatFile::Open(oat_location, oat_location, nullptr, !Runtime::Current()->IsCompiler(),
1638 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001639}
1640
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001641static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001642 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001643 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1644
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001645 DCHECK(obj != nullptr);
1646 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001647
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001648 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001649 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001650 if (!method->IsNative()) {
1651 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1652 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001653 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1654 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001655 }
1656 }
1657 }
1658}
1659
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001660void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001661 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001662 CHECK(!init_done_);
1663
Mathieu Chartier590fee92013-09-13 13:46:47 -07001664 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001665 gc::Heap* heap = Runtime::Current()->GetHeap();
1666 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001667 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001668 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001669 OatFile& oat_file = GetImageOatFile(space);
1670 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1671 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001672 const char* image_file_location = oat_file.GetOatHeader().
1673 GetStoreValueByKey(OatHeader::kImageLocationKey);
1674 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001675 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1676 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001677 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1678 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001679 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001680 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001681 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1682 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1683 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001684
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001685 StackHandleScope<1> hs(self);
1686 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1687 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1688 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001689 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001690
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001691 // Special case of setting up the String class early so that we can test arbitrary objects
1692 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001693 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001694
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001695 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001696 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001697 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001698 StackHandleScope<1> hs(self);
1699 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001700 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001701 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1702 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001703 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001704 std::string error_msg;
1705 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001706 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001707 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001708 << " from within oat file " << oat_file.GetLocation()
1709 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001710 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001711
1712 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1713
1714 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001715 }
1716
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001717 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1718 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001719 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001720
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001721 // Set entry point to interpreter if in InterpretOnly mode.
1722 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001723 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001724 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001725 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001726
1727 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001728 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001729 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001730
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001731 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001732 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1733 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001734 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001735 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001736 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001737 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1738 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1739 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1740 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1741 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1742 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1743 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1744 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1745 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1746 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001747
Ian Rogers98379392014-02-24 16:53:16 -08001748 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001749
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001750 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001751}
1752
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001753void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1754 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1755 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001756 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1757 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001758 }
1759 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1760 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001761 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1762 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1763 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1764 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001765 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1766 // corresponding object. This is slow, but luckily for us, this may only happen with a
1767 // concurrent moving GC.
1768 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1769 it != end && it->first == pair.first; ++it) {
1770 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001771 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1772 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001773 }
1774 }
1775 }
1776 }
1777 }
1778 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1779 new_class_roots_.clear();
1780 }
1781 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1782 log_new_class_table_roots_ = true;
1783 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1784 log_new_class_table_roots_ = false;
1785 }
1786 // We deliberately ignore the class roots in the image since we
1787 // handle image roots by using the MS/CMS rescanning of dirty cards.
1788}
1789
Brian Carlstroma663ea52011-08-19 23:33:41 -07001790// Keep in sync with InitCallback. Anything we visit, we need to
1791// reinit references to when reinitializing a ClassLinker from a
1792// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001793void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001794 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001795 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001796 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001797 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001798 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001799 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1800 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001801 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001802 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1803 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001804 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001805 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001806 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001807 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1808 new_dex_cache_roots_.clear();
1809 }
1810 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1811 log_new_dex_caches_roots_ = true;
1812 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1813 log_new_dex_caches_roots_ = false;
1814 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001815 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001816 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001817 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1818 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001819 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001820 if (!find_array_class_cache_[i].IsNull()) {
1821 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001822 }
1823 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001824}
1825
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001826void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1827 if (dex_cache_image_class_lookup_required_) {
1828 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001829 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001830 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001831 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001832 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1833 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001834 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001835 return;
1836 }
1837 }
1838}
1839
Ian Rogersdbf3be02014-08-29 15:40:08 -07001840static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001841 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001842 classes->insert(c);
1843 return true;
1844}
1845
Ian Rogersdbf3be02014-08-29 15:40:08 -07001846struct GetClassesVisitorArrayArg {
1847 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1848 int32_t index;
1849 bool success;
1850};
1851
1852static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1853 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1854 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1855 if (arg->index < (*arg->classes)->GetLength()) {
1856 (*arg->classes)->Set(arg->index, c);
1857 arg->index++;
1858 return true;
1859 } else {
1860 arg->success = false;
1861 return false;
1862 }
1863}
1864
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001865void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001866 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1867 // is avoiding duplicates.
1868 if (!kMovingClasses) {
1869 std::set<mirror::Class*> classes;
1870 VisitClasses(GetClassesVisitorSet, &classes);
1871 for (mirror::Class* klass : classes) {
1872 if (!visitor(klass, arg)) {
1873 return;
1874 }
1875 }
1876 } else {
1877 Thread* self = Thread::Current();
1878 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001879 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001880 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1881 GetClassesVisitorArrayArg local_arg;
1882 local_arg.classes = &classes;
1883 local_arg.success = false;
1884 // We size the array assuming classes won't be added to the class table during the visit.
1885 // If this assumption fails we iterate again.
1886 while (!local_arg.success) {
1887 size_t class_table_size;
1888 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001889 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001890 class_table_size = class_table_.size();
1891 }
1892 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1893 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1894 classes.Assign(
1895 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1896 CHECK(classes.Get() != nullptr); // OOME.
1897 local_arg.index = 0;
1898 local_arg.success = true;
1899 VisitClasses(GetClassesVisitorArray, &local_arg);
1900 }
1901 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1902 // If the class table shrank during creation of the clases array we expect null elements. If
1903 // the class table grew then the loop repeats. If classes are created after the loop has
1904 // finished then we don't visit.
1905 mirror::Class* klass = classes->Get(i);
1906 if (klass != nullptr && !visitor(klass, arg)) {
1907 return;
1908 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001909 }
1910 }
1911}
1912
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001913ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001914 mirror::Class::ResetClass();
1915 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001916 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001917 mirror::ArtField::ResetClass();
1918 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001919 mirror::BooleanArray::ResetArrayClass();
1920 mirror::ByteArray::ResetArrayClass();
1921 mirror::CharArray::ResetArrayClass();
1922 mirror::DoubleArray::ResetArrayClass();
1923 mirror::FloatArray::ResetArrayClass();
1924 mirror::IntArray::ResetArrayClass();
1925 mirror::LongArray::ResetArrayClass();
1926 mirror::ShortArray::ResetArrayClass();
1927 mirror::Throwable::ResetClass();
1928 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001929 STLDeleteElements(&boot_class_path_);
1930 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001931}
1932
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001933mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001934 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001935 StackHandleScope<16> hs(self);
1936 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1937 Handle<mirror::DexCache> dex_cache(
1938 hs.NewHandle(down_cast<mirror::DexCache*>(
1939 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1940 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001941 if (dex_cache.Get() == nullptr) {
1942 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001943 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001944 Handle<mirror::String>
1945 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001946 if (location.Get() == nullptr) {
1947 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001948 }
Ian Rogers700a4022014-05-19 16:49:03 -07001949 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001950 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001951 if (strings.Get() == nullptr) {
1952 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001953 }
Ian Rogers700a4022014-05-19 16:49:03 -07001954 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001955 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001956 if (types.Get() == nullptr) {
1957 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001958 }
Ian Rogers700a4022014-05-19 16:49:03 -07001959 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001960 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001961 if (methods.Get() == nullptr) {
1962 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001963 }
Ian Rogers700a4022014-05-19 16:49:03 -07001964 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001965 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001966 if (fields.Get() == nullptr) {
1967 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001968 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001969 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1970 fields.Get());
1971 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001972}
1973
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001974mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001975 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001976 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001977 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001978 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001979 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001980 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1981 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001982 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001983 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001984 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001985 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001986 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001987}
1988
Ian Rogers6fac4472014-02-25 17:01:10 -08001989mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001990 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001991}
1992
Brian Carlstromea46f952013-07-30 01:26:50 -07001993mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001994 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001995 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001996}
1997
Brian Carlstromea46f952013-07-30 01:26:50 -07001998mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001999 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002000 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002001}
2002
Mathieu Chartier590fee92013-09-13 13:46:47 -07002003mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2004 Thread* self, size_t length) {
2005 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2006 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002007}
2008
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002009mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2010 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002011 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002012
2013 // For temporary classes we must wait for them to be retired.
2014 if (init_done_ && klass->IsTemp()) {
2015 CHECK(!klass->IsResolved());
2016 if (klass->IsErroneous()) {
2017 ThrowEarlierClassFailure(klass);
2018 return nullptr;
2019 }
2020 StackHandleScope<1> hs(self);
2021 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2022 ObjectLock<mirror::Class> lock(self, h_class);
2023 // Loop and wait for the resolving thread to retire this class.
2024 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2025 lock.WaitIgnoringInterrupts();
2026 }
2027 if (h_class->IsErroneous()) {
2028 ThrowEarlierClassFailure(h_class.Get());
2029 return nullptr;
2030 }
2031 CHECK(h_class->IsRetired());
2032 // Get the updated class from class table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002033 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002034 }
2035
Brian Carlstromaded5f72011-10-07 17:15:04 -07002036 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002037 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002038 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002039 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2040 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002042 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2043 ThrowClassCircularityError(h_class.Get());
2044 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002045 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002046 }
2047 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002048 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002049 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002050 }
2051 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002052
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002053 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002054 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002055 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002056 }
2057 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002058 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002059 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002060 return klass;
2061}
2062
Ian Rogers68b56852014-08-29 20:19:11 -07002063typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2064
2065// Search a collection of DexFiles for a descriptor
2066ClassPathEntry FindInClassPath(const char* descriptor,
2067 const std::vector<const DexFile*>& class_path) {
2068 for (size_t i = 0; i != class_path.size(); ++i) {
2069 const DexFile* dex_file = class_path[i];
2070 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002071 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002072 return ClassPathEntry(dex_file, dex_class_def);
2073 }
2074 }
2075 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002076 return ClassPathEntry(static_cast<const DexFile*>(nullptr),
2077 static_cast<const DexFile::ClassDef*>(nullptr));
Ian Rogers68b56852014-08-29 20:19:11 -07002078}
2079
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002080mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2081 Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002082 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002083 if (class_loader->GetClass() !=
2084 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2085 class_loader->GetParent()->GetClass() !=
2086 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2087 return nullptr;
2088 }
2089 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2090 // Check if this would be found in the parent boot class loader.
2091 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002092 mirror::Class* klass = LookupClass(self, descriptor, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002093 if (klass != nullptr) {
2094 return EnsureResolved(self, descriptor, klass);
2095 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002096 klass = DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002097 *pair.second);
2098 if (klass != nullptr) {
2099 return klass;
2100 }
2101 CHECK(self->IsExceptionPending()) << descriptor;
2102 self->ClearException();
2103 } else {
2104 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2105 StackHandleScope<3> hs(self);
2106 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2107 // We need to get the DexPathList and loop through it.
2108 Handle<mirror::ArtField> cookie_field =
2109 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2110 Handle<mirror::ArtField> dex_file_field =
2111 hs.NewHandle(
2112 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList$Element_dexFile));
2113 mirror::Object* dex_path_list =
2114 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2115 GetObject(class_loader.Get());
2116 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2117 cookie_field.Get() != nullptr) {
2118 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2119 mirror::Object* dex_elements_obj =
2120 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2121 GetObject(dex_path_list);
2122 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2123 // at the mCookie which is a DexFile vector.
2124 if (dex_elements_obj != nullptr) {
2125 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2126 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2127 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2128 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2129 if (element == nullptr) {
2130 // Should never happen, fall back to java code to throw a NPE.
2131 break;
2132 }
2133 mirror::Object* dex_file = dex_file_field->GetObject(element);
2134 if (dex_file != nullptr) {
2135 const uint64_t cookie = cookie_field->GetLong(dex_file);
2136 auto* dex_files =
2137 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2138 if (dex_files == nullptr) {
2139 // This should never happen so log a warning.
2140 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2141 break;
2142 }
2143 for (const DexFile* dex_file : *dex_files) {
2144 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
2145 if (dex_class_def != nullptr) {
2146 RegisterDexFile(*dex_file);
2147 mirror::Class* klass =
Ian Rogers7b078e82014-09-10 14:44:24 -07002148 DefineClass(self, descriptor, class_loader, *dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002149 if (klass == nullptr) {
2150 CHECK(self->IsExceptionPending()) << descriptor;
2151 self->ClearException();
2152 return nullptr;
2153 }
2154 return klass;
2155 }
2156 }
2157 }
2158 }
2159 }
2160 }
2161 }
2162 return nullptr;
2163}
2164
Ian Rogers98379392014-02-24 16:53:16 -08002165mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002166 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002167 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002168 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002169 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002170 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002171 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2172 // for primitive classes that aren't backed by dex files.
2173 return FindPrimitiveClass(descriptor[0]);
2174 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002175 // Find the class in the loaded classes table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002176 mirror::Class* klass = LookupClass(self, descriptor, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002177 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002178 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002179 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002180 // Class is not yet loaded.
2181 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08002182 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002183 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002184 // The boot class loader, search the boot class path.
Ian Rogers68b56852014-08-29 20:19:11 -07002185 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2186 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002187 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2188 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002189 } else {
2190 // The boot class loader is searched ahead of the application class loader, failures are
2191 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2192 // trigger the chaining with a proper stack trace.
2193 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2194 self->SetException(ThrowLocation(), pre_allocated);
2195 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002196 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002197 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002198 // First try with the bootstrap class loader.
2199 if (class_loader.Get() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002200 klass = LookupClass(self, descriptor, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002201 if (klass != nullptr) {
2202 return EnsureResolved(self, descriptor, klass);
2203 }
2204 }
Ian Rogers63557452014-06-04 16:57:15 -07002205 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2206 // a NoClassDefFoundError being allocated.
Ian Rogers68b56852014-08-29 20:19:11 -07002207 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2208 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002209 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2210 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002211 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002212 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002213 const std::vector<const DexFile*>* class_path;
2214 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002215 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002216 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002217 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002218 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2219 }
Ian Rogers68b56852014-08-29 20:19:11 -07002220 pair = FindInClassPath(descriptor, *class_path);
2221 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002222 return DefineClass(self, descriptor, class_loader, *pair.first, *pair.second);
2223 } else {
2224 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2225 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2226 self->SetException(ThrowLocation(), pre_allocated);
2227 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002228 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002229 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002230 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002231 mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, class_loader);
2232 if (klass != nullptr) {
2233 return klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002234 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002235 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002236 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002237 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002238 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002239 {
2240 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002241 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2242 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002243 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002244 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002245 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002246 }
Ian Rogers68b56852014-08-29 20:19:11 -07002247 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002248 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2249 WellKnownClasses::java_lang_ClassLoader_loadClass,
2250 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002251 }
Ian Rogers98379392014-02-24 16:53:16 -08002252 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002253 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002254 return nullptr;
2255 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002256 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002257 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002258 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002259 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002260 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002261 // success, return mirror::Class*
2262 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002263 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002264 }
2265
Elliott Hughes82914b62012-04-09 15:56:29 -07002266 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002267 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002268}
2269
Ian Rogers7b078e82014-09-10 14:44:24 -07002270mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002271 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002272 const DexFile& dex_file,
2273 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002274 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002275 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002276 bool should_allocate = false;
2277
Brian Carlstromaded5f72011-10-07 17:15:04 -07002278 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002279 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002280 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002281 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002282 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002283 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002284 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002285 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002286 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002287 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2288 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002289 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002291 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002292 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002293 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002294 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002295 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002296 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002297 }
2298 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002299 should_allocate = true;
2300 }
2301
2302 if (should_allocate) {
2303 // Allocate a class with the status of not ready.
2304 // Interface object should get the right size here. Regular class will
2305 // figure out the right size later and be replaced with one of the right
2306 // size when the class becomes resolved.
2307 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002308 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002309 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002310 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002311 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002312 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002313 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002314 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002315 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002316 if (self->IsExceptionPending()) {
2317 // An exception occured during load, set status to erroneous while holding klass' lock in case
2318 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002319 if (!klass->IsErroneous()) {
2320 klass->SetStatus(mirror::Class::kStatusError, self);
2321 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002322 return nullptr;
2323 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002324 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002325
Mathieu Chartier590fee92013-09-13 13:46:47 -07002326 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002327 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07002328 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002329 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2330 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002331 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002332 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002333
Brian Carlstromaded5f72011-10-07 17:15:04 -07002334 // Finish loading (if necessary) by finding parents
2335 CHECK(!klass->IsLoaded());
2336 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2337 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002338 if (!klass->IsErroneous()) {
2339 klass->SetStatus(mirror::Class::kStatusError, self);
2340 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002341 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002342 }
2343 CHECK(klass->IsLoaded());
2344 // Link the class (if necessary)
2345 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002346 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002347 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002348
2349 mirror::Class* new_class = nullptr;
2350 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002351 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002352 if (!klass->IsErroneous()) {
2353 klass->SetStatus(mirror::Class::kStatusError, self);
2354 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002355 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002356 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002357 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002358 CHECK(new_class != nullptr) << descriptor;
2359 CHECK(new_class->IsResolved()) << descriptor;
2360
2361 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002362
2363 /*
2364 * We send CLASS_PREPARE events to the debugger from here. The
2365 * definition of "preparation" is creating the static fields for a
2366 * class and initializing them to the standard default values, but not
2367 * executing any code (that comes later, during "initialization").
2368 *
2369 * We did the static preparation in LinkClass.
2370 *
2371 * The class has been prepared and resolved but possibly not yet verified
2372 * at this point.
2373 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002374 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002375
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002376 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002377}
2378
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002379uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2380 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002381 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002382 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002383 size_t num_8 = 0;
2384 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002385 size_t num_32 = 0;
2386 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002387 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002388 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2389 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002390 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002391 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002392 switch (c) {
2393 case 'L':
2394 case '[':
2395 num_ref++;
2396 break;
2397 case 'J':
2398 case 'D':
2399 num_64++;
2400 break;
2401 case 'I':
2402 case 'F':
2403 num_32++;
2404 break;
2405 case 'S':
2406 case 'C':
2407 num_16++;
2408 break;
2409 case 'B':
2410 case 'Z':
2411 num_8++;
2412 break;
2413 default:
2414 LOG(FATAL) << "Unknown descriptor: " << c;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002415 }
2416 }
2417 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002418 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002419}
2420
Ian Rogers97b52f82014-08-14 11:34:07 -07002421OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2422 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002423 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002424 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2425 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002426 *found = false;
2427 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002428 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002429 *found = true;
2430 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002431}
2432
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002433static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2434 uint32_t method_idx) {
2435 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2436 const byte* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002437 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002438 ClassDataItemIterator it(dex_file, class_data);
2439 // Skip fields
2440 while (it.HasNextStaticField()) {
2441 it.Next();
2442 }
2443 while (it.HasNextInstanceField()) {
2444 it.Next();
2445 }
2446 // Process methods
2447 size_t class_def_method_index = 0;
2448 while (it.HasNextDirectMethod()) {
2449 if (it.GetMemberIndex() == method_idx) {
2450 return class_def_method_index;
2451 }
2452 class_def_method_index++;
2453 it.Next();
2454 }
2455 while (it.HasNextVirtualMethod()) {
2456 if (it.GetMemberIndex() == method_idx) {
2457 return class_def_method_index;
2458 }
2459 class_def_method_index++;
2460 it.Next();
2461 }
2462 DCHECK(!it.HasNext());
2463 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2464 return 0;
2465}
2466
Ian Rogers97b52f82014-08-14 11:34:07 -07002467const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002468 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002469 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002470 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002471 size_t oat_method_index;
2472 if (method->IsStatic() || method->IsDirect()) {
2473 // Simple case where the oat method index was stashed at load time.
2474 oat_method_index = method->GetMethodIndex();
2475 } else {
2476 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2477 // by search for its position in the declared virtual methods.
2478 oat_method_index = declaring_class->NumDirectMethods();
2479 size_t end = declaring_class->NumVirtualMethods();
2480 bool found = false;
2481 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002482 // Check method index instead of identity in case of duplicate method definitions.
2483 if (method->GetDexMethodIndex() ==
2484 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002485 found = true;
2486 break;
2487 }
Ian Rogersf320b632012-03-13 18:47:47 -07002488 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002489 }
2490 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2491 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002492 DCHECK_EQ(oat_method_index,
2493 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002494 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002495 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002496 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2497 declaring_class->GetDexClassDefIndex(),
2498 found);
2499 if (!found) {
2500 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002501 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002502 *found = true;
2503 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002504}
2505
2506// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002507const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002508 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002509 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002510 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002511 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002512 bool found;
2513 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002514 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002515 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002516 result = oat_method.GetQuickCode();
2517 }
2518
Ian Rogersef7d42f2014-01-06 12:55:46 -08002519 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002520 if (method->IsNative()) {
2521 // No code and native? Use generic trampoline.
2522 result = GetQuickGenericJniTrampoline();
2523 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002524 // No code? Do we expect portable code?
2525 result = GetQuickToPortableBridge();
2526 } else {
2527 // No code? You must mean to go into the interpreter.
2528 result = GetQuickToInterpreterBridge();
2529 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002530 }
2531 return result;
TDYa12785321912012-04-01 15:24:56 -07002532}
2533
Ian Rogersef7d42f2014-01-06 12:55:46 -08002534const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2535 bool* have_portable_code) {
2536 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2537 *have_portable_code = false;
2538 if (method->IsProxyMethod()) {
2539 return GetPortableProxyInvokeHandler();
2540 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002541 bool found;
2542 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002543 const void* result = nullptr;
2544 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002545 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002546 result = oat_method.GetPortableCode();
2547 quick_code = oat_method.GetQuickCode();
2548 }
2549
Ian Rogersef7d42f2014-01-06 12:55:46 -08002550 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002551 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002552 // No code? You must mean to go into the interpreter.
2553 result = GetPortableToInterpreterBridge();
2554 } else {
2555 // No code? But there's quick code, so use a bridge.
2556 result = GetPortableToQuickBridge();
2557 }
2558 } else {
2559 *have_portable_code = true;
2560 }
2561 return result;
2562}
2563
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002564const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2565 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2566 return nullptr;
2567 }
2568 bool found;
2569 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2570 return found ? oat_method.GetQuickCode() : nullptr;
2571}
2572
2573const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2574 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2575 return nullptr;
2576 }
2577 bool found;
2578 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2579 return found ? oat_method.GetPortableCode() : nullptr;
2580}
2581
Ian Rogersef7d42f2014-01-06 12:55:46 -08002582const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2583 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002584 bool found;
2585 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2586 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002587 return nullptr;
2588 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002589 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002590 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002591}
2592
2593const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2594 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002595 bool found;
2596 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2597 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002598 return nullptr;
2599 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002600 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002601 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002602}
2603
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002604// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002605static bool NeedsInterpreter(
2606 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2607 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002608 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002609 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002610 // May return true for native code, in the case of generic JNI
2611 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002612 return true;
2613 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002614#ifdef ART_SEA_IR_MODE
2615 ScopedObjectAccess soa(Thread::Current());
2616 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2617 LOG(INFO) << "Found " << PrettyMethod(method);
2618 return false;
2619 }
2620#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002621 // If interpreter mode is enabled, every method (except native and proxy) must
2622 // be run with interpreter.
2623 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2624 !method->IsNative() && !method->IsProxyMethod();
2625}
2626
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002627void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002628 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002629 if (klass->NumDirectMethods() == 0) {
2630 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002631 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002632 Runtime* runtime = Runtime::Current();
2633 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002634 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2635 return; // OAT file unavailable.
2636 }
Ian Rogers19846512012-02-24 11:42:47 -08002637 }
Alex Light64ad14d2014-08-19 14:23:13 -07002638
Mathieu Chartierf8322842014-05-16 10:59:25 -07002639 const DexFile& dex_file = klass->GetDexFile();
2640 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002641 CHECK(dex_class_def != nullptr);
2642 const byte* class_data = dex_file.GetClassData(*dex_class_def);
2643 // There should always be class data if there were direct methods.
2644 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002645 ClassDataItemIterator it(dex_file, class_data);
2646 // Skip fields
2647 while (it.HasNextStaticField()) {
2648 it.Next();
2649 }
2650 while (it.HasNextInstanceField()) {
2651 it.Next();
2652 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002653 bool has_oat_class;
2654 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2655 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002656 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002657 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002658 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002659 if (!method->IsStatic()) {
2660 // Only update static methods.
2661 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002662 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002663 const void* portable_code = nullptr;
2664 const void* quick_code = nullptr;
2665 if (has_oat_class) {
2666 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2667 portable_code = oat_method.GetPortableCode();
2668 quick_code = oat_method.GetQuickCode();
2669 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002670 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2671 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002672 if (enter_interpreter) {
2673 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002674 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002675 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2676 quick_code = GetQuickGenericJniTrampoline();
Ian Rogers1a570662014-03-12 01:02:21 -07002677 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002678 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002679 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002680 quick_code = GetQuickToInterpreterBridge();
2681 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002682 } else {
2683 if (portable_code == nullptr) {
2684 portable_code = GetPortableToQuickBridge();
2685 } else {
2686 have_portable_code = true;
2687 }
2688 if (quick_code == nullptr) {
2689 quick_code = GetQuickToPortableBridge();
2690 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002691 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002692 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2693 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002694 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002695 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002696}
2697
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002698void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002699 const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002700 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002701 uint32_t method_index) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002702 if (Runtime::Current()->IsCompiler()) {
2703 // The following code only applies to a non-compiler runtime.
2704 return;
2705 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002706 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002707 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2708 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002709 if (oat_class != nullptr) {
2710 // Every kind of method should at least get an invoke stub from the oat_method.
2711 // non-abstract methods also get their code pointers.
2712 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2713 oat_method.LinkMethod(method.Get());
2714 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002715
Jeff Hao16743632013-05-08 10:59:04 -07002716 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002717 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002718 method->GetEntryPointFromQuickCompiledCode(),
2719 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002720 if (enter_interpreter && !method->IsNative()) {
Ian Rogers848871b2013-08-05 10:56:33 -07002721 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002722 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002723 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002724 }
2725
Brian Carlstrom92827a52011-10-10 15:50:01 -07002726 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002727 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2728 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002729 return;
2730 }
Ian Rogers19846512012-02-24 11:42:47 -08002731
Ian Rogersef7d42f2014-01-06 12:55:46 -08002732 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002733 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002734 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002735 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2736 // after initializing class (see ClassLinker::InitializeClass method).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002737 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline());
2738 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002739 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002740 if (!method->IsNative()) {
2741 // Set entry point from compiled code if there's no code or in interpreter only mode.
2742 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2743 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2744 } else {
2745 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline());
2746 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2747 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002748 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2749 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2750 have_portable_code = true;
2751 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2752 } else {
2753 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2754 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002755 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002756
Ian Rogers62d6c772013-02-27 08:32:07 -08002757 if (method->IsNative()) {
2758 // Unregistering restores the dlsym lookup stub.
2759 method->UnregisterNative(Thread::Current());
Andreas Gampe90546832014-03-12 18:07:19 -07002760
2761 if (enter_interpreter) {
2762 // We have a native method here without code. Then it should have either the GenericJni
2763 // trampoline as entrypoint (non-static), or the Resolution trampoline (static).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002764 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline()
Andreas Gampe9a6a99a2014-03-14 07:52:20 -07002765 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline());
Andreas Gampe90546832014-03-12 18:07:19 -07002766 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002767 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002768
Ian Rogers62d6c772013-02-27 08:32:07 -08002769 // Allow instrumentation its chance to hijack code.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002770 Runtime* runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002771 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002772 method->GetEntryPointFromQuickCompiledCode(),
2773 method->GetEntryPointFromPortableCompiledCode(),
2774 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002775}
2776
Fred Shih37f05ef2014-07-16 18:38:08 -07002777
Fred Shih37f05ef2014-07-16 18:38:08 -07002778
Ian Rogers7b078e82014-09-10 14:44:24 -07002779void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002780 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002781 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002782 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002783 CHECK(klass.Get() != nullptr);
2784 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002785 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002786 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002787 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002788
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002789 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002790 if (kUseBakerOrBrooksReadBarrier) {
2791 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002792 }
Andreas Gampe51829322014-08-25 15:05:04 -07002793 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002794 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002795 klass->SetAccessFlags(access_flags);
2796 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002797 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002798 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002799
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002800 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002801 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002802
Ian Rogers0571d352011-11-03 19:51:38 -07002803 const byte* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002804 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002805 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002806 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002807
Ian Rogers97b52f82014-08-14 11:34:07 -07002808
2809 bool has_oat_class = false;
2810 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2811 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2812 &has_oat_class);
2813 if (has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002814 LoadClassMembers(self, dex_file, class_data, klass, class_loader, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002815 }
2816 }
2817 if (!has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002818 LoadClassMembers(self, dex_file, class_data, klass, class_loader, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002819 }
2820}
2821
Ian Rogers7b078e82014-09-10 14:44:24 -07002822void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002823 const byte* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002824 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002825 mirror::ClassLoader* class_loader,
2826 const OatFile::OatClass* oat_class) {
2827 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002828 ClassDataItemIterator it(dex_file, class_data);
2829 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002830 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002831 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002832 CHECK(self->IsExceptionPending()); // OOME.
2833 return;
2834 }
2835 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002836 }
2837 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002838 mirror::ObjectArray<mirror::ArtField>* fields =
2839 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002840 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002841 CHECK(self->IsExceptionPending()); // OOME.
2842 return;
2843 }
2844 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002845 }
2846 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002847 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002848 StackHandleScope<1> hs(self);
2849 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002850 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002851 CHECK(self->IsExceptionPending()); // OOME.
2852 return;
2853 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002854 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002855 LoadField(dex_file, it, klass, sfield);
2856 }
2857 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002858 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002859 StackHandleScope<1> hs(self);
2860 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002861 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002862 CHECK(self->IsExceptionPending()); // OOME.
2863 return;
2864 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002865 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002866 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002867 }
2868
Ian Rogers0571d352011-11-03 19:51:38 -07002869 // Load methods.
2870 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002871 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002872 mirror::ObjectArray<mirror::ArtMethod>* directs =
2873 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002874 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002875 CHECK(self->IsExceptionPending()); // OOME.
2876 return;
2877 }
2878 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002879 }
Ian Rogers0571d352011-11-03 19:51:38 -07002880 if (it.NumVirtualMethods() != 0) {
2881 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002882 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2883 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002884 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002885 CHECK(self->IsExceptionPending()); // OOME.
2886 return;
2887 }
2888 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002889 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002890 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002891 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2892 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002893 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002894 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002895 StackHandleScope<1> hs(self);
2896 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002897 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002898 CHECK(self->IsExceptionPending()); // OOME.
2899 return;
2900 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002901 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002902 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002903 uint32_t it_method_index = it.GetMemberIndex();
2904 if (last_dex_method_index == it_method_index) {
2905 // duplicate case
2906 method->SetMethodIndex(last_class_def_method_index);
2907 } else {
2908 method->SetMethodIndex(class_def_method_index);
2909 last_dex_method_index = it_method_index;
2910 last_class_def_method_index = class_def_method_index;
2911 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002912 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002913 }
2914 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002915 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002916 StackHandleScope<1> hs(self);
2917 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002918 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002919 CHECK(self->IsExceptionPending()); // OOME.
2920 return;
2921 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002922 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002923 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002924 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002925 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002926 }
2927 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002928}
2929
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002930void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002931 Handle<mirror::Class> klass,
2932 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002933 uint32_t field_idx = it.GetMemberIndex();
2934 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002935 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002936 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002937}
2938
Brian Carlstromea46f952013-07-30 01:26:50 -07002939mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002940 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002941 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002942 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002943 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002944 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002945
Brian Carlstromea46f952013-07-30 01:26:50 -07002946 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002947 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002948 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002949 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002950 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002951 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002952
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002953 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002954 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002955 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002956 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002957
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002958 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002959 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002960 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002961
Andreas Gampe51829322014-08-25 15:05:04 -07002962 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002963
Ian Rogersdfb325e2013-10-30 01:00:44 -07002964 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002965 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002966 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2967 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002968 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002969 klass->SetFinalizable();
2970 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002971 std::string temp;
2972 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002973 // The Enum class declares a "final" finalize() method to prevent subclasses from
2974 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2975 // subclasses, so we exclude it here.
2976 // We also want to avoid setting the flag on Object, where we know that finalize() is
2977 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002978 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2979 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002980 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002981 }
2982 }
2983 }
2984 } else if (method_name[0] == '<') {
2985 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002986 bool is_init = (strcmp("<init>", method_name) == 0);
2987 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002988 if (UNLIKELY(!is_init && !is_clinit)) {
2989 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2990 } else {
2991 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2992 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002993 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002994 access_flags |= kAccConstructor;
2995 }
2996 }
2997 }
2998 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002999
Mathieu Chartier66f19252012-09-18 08:57:04 -07003000 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07003001}
3002
Ian Rogers7b078e82014-09-10 14:44:24 -07003003void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003004 StackHandleScope<1> hs(self);
3005 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003006 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3007 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003008 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003009}
3010
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003011void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003012 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003013 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003014 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003015 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003016}
3017
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003018bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003019 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07003020 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003021 mirror::DexCache* dex_cache = GetDexCache(i);
3022 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08003023 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003024 }
3025 }
3026 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003027}
3028
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003029bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003030 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003031 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003032}
3033
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003034void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003035 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003036 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003037 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003038 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3039 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003040 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003041 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003042 if (log_new_dex_caches_roots_) {
3043 // TODO: This is not safe if we can remove dex caches.
3044 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3045 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003046}
3047
Brian Carlstromaded5f72011-10-07 17:15:04 -07003048void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003049 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003050 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003051 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003052 if (IsDexFileRegisteredLocked(dex_file)) {
3053 return;
3054 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003055 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003056 // Don't alloc while holding the lock, since allocation may need to
3057 // suspend all threads and another thread may need the dex_lock_ to
3058 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003059 StackHandleScope<1> hs(self);
3060 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003061 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3062 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003063 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003064 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003065 if (IsDexFileRegisteredLocked(dex_file)) {
3066 return;
3067 }
3068 RegisterDexFileLocked(dex_file, dex_cache);
3069 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003070}
3071
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003072void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003073 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003074 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003075 RegisterDexFileLocked(dex_file, dex_cache);
3076}
3077
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003078mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003079 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003080 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003081 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003082 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003083 if (dex_cache->GetDexFile() == &dex_file) {
3084 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003085 }
3086 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003087 // Search matching by location name.
3088 std::string location(dex_file.GetLocation());
3089 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003090 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003091 if (dex_cache->GetDexFile()->GetLocation() == location) {
3092 return dex_cache;
3093 }
3094 }
3095 // Failure, dump diagnostic and abort.
3096 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003097 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003098 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3099 }
3100 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003101 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003102}
3103
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003104void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003105 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003106 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003107 mirror::DexCache* dex_cache = GetDexCache(i);
3108 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003109 }
3110}
3111
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003112mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003113 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003114 if (UNLIKELY(klass == nullptr)) {
3115 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003116 }
3117 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003118}
3119
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003120mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3121 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003122 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003123 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003124 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003125 StackHandleScope<1> hs(self);
3126 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003127 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003128 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003129 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003130 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3131 const char* descriptor = Primitive::Descriptor(type);
3132 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003133 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003134 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003135}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003136
Brian Carlstrombe977852011-07-19 14:54:54 -07003137// Create an array class (i.e. the class object for the array, not the
3138// array itself). "descriptor" looks like "[C" or "[[[[B" or
3139// "[Ljava/lang/String;".
3140//
3141// If "descriptor" refers to an array of primitives, look up the
3142// primitive type's internally-generated class object.
3143//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003144// "class_loader" is the class loader of the class that's referring to
3145// us. It's used to ensure that we're looking for the element type in
3146// the right context. It does NOT become the class loader for the
3147// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003148//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003149// Returns nullptr with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08003150mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003151 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003152 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003153 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003154 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003155 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3156 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003157 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003158 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003159 // We need to accept erroneous classes as component types.
Ian Rogers7b078e82014-09-10 14:44:24 -07003160 component_type.Assign(LookupClass(self, descriptor + 1, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003161 if (component_type.Get() == nullptr) {
3162 DCHECK(self->IsExceptionPending());
3163 return nullptr;
3164 } else {
3165 self->ClearException();
3166 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003167 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003168 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3169 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3170 return nullptr;
3171 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003172 // See if the component type is already loaded. Array classes are
3173 // always associated with the class loader of their underlying
3174 // element type -- an array of Strings goes with the loader for
3175 // java/lang/String -- so we need to look for it there. (The
3176 // caller should have checked for the existence of the class
3177 // before calling here, but they did so with *their* class loader,
3178 // not the component type's loader.)
3179 //
3180 // If we find it, the caller adds "loader" to the class' initiating
3181 // loader list, which should prevent us from going through this again.
3182 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003183 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003184 // are the same, because our caller (FindClass) just did the
3185 // lookup. (Even if we get this wrong we still have correct behavior,
3186 // because we effectively do this lookup again when we add the new
3187 // class to the hash table --- necessary because of possible races with
3188 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003189 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003190 mirror::Class* new_class = LookupClass(self, descriptor, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003191 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003192 return new_class;
3193 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003194 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003195
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003196 // Fill out the fields in the Class.
3197 //
3198 // It is possible to execute some methods against arrays, because
3199 // all arrays are subclasses of java_lang_Object_, so we need to set
3200 // up a vtable. We can just point at the one in java_lang_Object_.
3201 //
3202 // Array classes are simple enough that we don't need to do a full
3203 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003204 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003205 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003206 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003207 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003208 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003209 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003210 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003211 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003212 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003213 } else if (strcmp(descriptor,
3214 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003215 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003216 } else if (strcmp(descriptor,
3217 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003218 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003219 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003220 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003221 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003222 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003223 }
3224 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003225 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003226 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003227 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003228 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003229 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003230 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003231 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003232 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003233 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003234 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003235 new_class->SetSuperClass(java_lang_Object);
3236 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003237 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003238 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003239 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
3240 new_class->PopulateEmbeddedImtAndVTable();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003241 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003242 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003243 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003244
3245
3246 // All arrays have java/lang/Cloneable and java/io/Serializable as
3247 // interfaces. We need to set that up here, so that stuff like
3248 // "instanceof" works right.
3249 //
3250 // Note: The GC could run during the call to FindSystemClass,
3251 // so we need to make sure the class object is GC-valid while we're in
3252 // there. Do this by clearing the interface list so the GC will just
3253 // think that the entries are null.
3254
3255
3256 // Use the single, global copies of "interfaces" and "iftable"
3257 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003258 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003259 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003260 CHECK(array_iftable != nullptr);
3261 new_class->SetIfTable(array_iftable);
3262 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003263
Elliott Hughes00626c22013-06-14 15:04:14 -07003264 // Inherit access flags from the component type.
3265 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3266 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3267 access_flags &= kAccJavaFlagsMask;
3268 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003269 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003270 access_flags |= kAccAbstract | kAccFinal;
3271 access_flags &= ~kAccInterface;
3272
3273 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003274
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003275 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003276 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003277 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003278 }
3279 // Another thread must have loaded the class after we
3280 // started but before we finished. Abandon what we've
3281 // done.
3282 //
3283 // (Yes, this happens.)
3284
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003285 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003286}
3287
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003288mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003289 switch (type) {
3290 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003291 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003292 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003293 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003294 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003295 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003296 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003297 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003298 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003299 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003300 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003301 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003302 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003303 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003304 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003305 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003306 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003307 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003308 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003309 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003310 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003311 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003312 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003313 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003314}
3315
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003316mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3317 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003318 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003319 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003320 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003321 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003322 source += " from ";
3323 source += dex_cache->GetLocation()->ToModifiedUtf8();
3324 }
3325 LOG(INFO) << "Loaded class " << descriptor << source;
3326 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003327 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003328 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003329 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003330 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003331 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003332 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003333 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003334 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003335 // Check a class loaded with the system class loader matches one in the image if the class
3336 // is in the image.
3337 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003338 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003339 CHECK(klass == existing);
3340 }
3341 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003342 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003343 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003344 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003345 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003346 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003347 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003348}
3349
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003350mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3351 size_t hash) {
3352 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3353 mirror::Class* existing =
3354 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3355
3356 if (existing == nullptr) {
3357 CHECK(klass->IsProxyClass());
3358 return nullptr;
3359 }
3360
3361 CHECK_NE(existing, klass) << descriptor;
3362 CHECK(!existing->IsResolved()) << descriptor;
3363 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3364
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003365 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3366 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003367 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07003368 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003369 class_table_.erase(it);
3370 break;
3371 }
3372 }
3373
3374 CHECK(!klass->IsTemp()) << descriptor;
3375 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3376 dex_cache_image_class_lookup_required_) {
3377 // Check a class loaded with the system class loader matches one in the image if the class
3378 // is in the image.
3379 existing = LookupClassFromImage(descriptor);
3380 if (existing != nullptr) {
3381 CHECK(klass == existing) << descriptor;
3382 }
3383 }
3384 VerifyObject(klass);
3385
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003386 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003387 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003388 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003389 }
3390
3391 return existing;
3392}
3393
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003394bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003395 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003396 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07003397 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3398 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003399 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003400 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003401 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003402 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08003403 return true;
3404 }
3405 }
3406 return false;
3407}
3408
Ian Rogers7b078e82014-09-10 14:44:24 -07003409mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003410 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003411 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003412 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003413 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003414 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003415 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003416 return result;
3417 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003418 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003419 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3420 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003421 } else {
3422 // Lookup failed but need to search dex_caches_.
3423 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003424 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003425 InsertClass(descriptor, result, hash);
3426 } else {
3427 // Searching the image dex files/caches failed, we don't want to get into this situation
3428 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3429 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003430 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003431 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3432 MoveImageClassesToClassTable();
3433 }
3434 }
3435 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003436 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003437}
3438
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003439mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3440 const mirror::ClassLoader* class_loader,
3441 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003442 auto end = class_table_.end();
3443 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003444 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003445 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003446 if (kIsDebugBuild) {
3447 // Check for duplicates in the table.
3448 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003449 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003450 CHECK(!(klass2->GetClassLoader() == class_loader &&
3451 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003452 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3453 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003454 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003455 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003456 return klass;
3457 }
3458 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003459 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003460}
3461
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003462static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3463 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3464 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003465 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003466 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3467 return root->AsObjectArray<mirror::DexCache>();
3468}
3469
3470void ClassLinker::MoveImageClassesToClassTable() {
3471 Thread* self = Thread::Current();
3472 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3473 if (!dex_cache_image_class_lookup_required_) {
3474 return; // All dex cache classes are already in the class table.
3475 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003476 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003477 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003478 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003479 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3480 mirror::DexCache* dex_cache = dex_caches->Get(i);
3481 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3482 for (int32_t j = 0; j < types->GetLength(); j++) {
3483 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003484 if (klass != nullptr) {
3485 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003486 const char* descriptor = klass->GetDescriptor(&temp);
3487 size_t hash = Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003488 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3489 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003490 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3491 << PrettyClassAndClassLoader(klass);
3492 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003493 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003494 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003495 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003496 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003497 }
3498 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003499 }
3500 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003501 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003502}
3503
3504mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003505 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003506 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3507 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3508 mirror::DexCache* dex_cache = dex_caches->Get(i);
3509 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003510 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003511 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003512 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003513 const DexFile::TypeId* type_id =
3514 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003515 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003516 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3517 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003518 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003519 return klass;
3520 }
3521 }
3522 }
3523 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003524 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003525}
3526
3527void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3528 result.clear();
3529 if (dex_cache_image_class_lookup_required_) {
3530 MoveImageClassesToClassTable();
3531 }
3532 size_t hash = Hash(descriptor);
3533 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003534 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003535 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003536 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003537 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003538 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003539 }
3540 }
3541}
3542
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003543void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003544 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003545 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003546
Ian Rogers9ffb0392012-09-10 11:56:50 -07003547 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003548 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003549 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003550 return;
3551 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003552 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3553 return;
3554 }
jeffhao98eacac2011-09-14 16:11:53 -07003555
Ian Rogers9ffb0392012-09-10 11:56:50 -07003556 // The class might already be erroneous, for example at compile time if we attempted to verify
3557 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003558 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003559 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003560 return;
3561 }
3562
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003563 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003564 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003565 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003566 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003567 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003568 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003569 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003570 }
jeffhao98eacac2011-09-14 16:11:53 -07003571
Jeff Hao4a200f52014-04-01 14:58:49 -07003572 // Skip verification if disabled.
3573 if (!Runtime::Current()->IsVerificationEnabled()) {
3574 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003575 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003576 return;
3577 }
3578
Ian Rogers9ffb0392012-09-10 11:56:50 -07003579 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003580 StackHandleScope<2> hs(self);
3581 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003582 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003583 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003584 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003585
3586 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003587 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003588 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003589 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003590 std::string error_msg(
3591 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3592 PrettyDescriptor(klass.Get()).c_str(),
3593 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003594 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003595 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3596 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003597 self->ClearException();
3598 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003599 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3600 if (cause.Get() != nullptr) {
3601 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003602 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003603 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003604 if (Runtime::Current()->IsCompiler()) {
3605 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3606 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003607 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003608 return;
3609 }
3610 }
3611
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003612 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003613 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003614 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003615 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003616 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003617 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003618 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003619 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003620 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3621 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003622 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003623 return;
3624 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003625 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003626 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003627 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003628 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003629 Runtime::Current()->IsCompiler(),
3630 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003631 }
3632 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003633 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003634 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003635 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3636 << " because: " << error_msg;
3637 }
Ian Rogers1f539342012-10-03 21:09:42 -07003638 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003639 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003640 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003641 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003642 // Even though there were no verifier failures we need to respect whether the super-class
3643 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003644 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003645 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003646 } else {
3647 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003648 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003649 // Pretend a soft failure occured so that we don't consider the class verified below.
3650 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003651 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003652 } else {
3653 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3654 // Soft failures at compile time should be retried at runtime. Soft
3655 // failures at runtime will be handled by slow paths in the generated
3656 // code. Set status accordingly.
3657 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003658 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003659 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003660 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003661 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3662 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003663 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003664 }
3665 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003666 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003667 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003668 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3669 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003670 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003671 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003672 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003673 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003674 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003675 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003676 // Let the interpreter know it by setting the kAccPreverified flag onto each
3677 // method.
3678 // Note: we're going here during compilation and at runtime. When we set the
3679 // kAccPreverified flag when compiling image classes, the flag is recorded
3680 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003681 EnsurePreverifiedMethods(klass);
3682 }
3683}
3684
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003685void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003686 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003687 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003688 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003689 }
jeffhao98eacac2011-09-14 16:11:53 -07003690}
3691
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003692bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3693 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003694 // If we're compiling, we can only verify the class using the oat file if
3695 // we are not compiling the image or if the class we're verifying is not part of
3696 // the app. In other words, we will only check for preverification of bootclasspath
3697 // classes.
3698 if (Runtime::Current()->IsCompiler()) {
3699 // Are we compiling the bootclasspath?
3700 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3701 return false;
3702 }
3703 // We are compiling an app (not the image).
3704
3705 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003706 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003707 return false;
3708 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003709 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003710
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003711 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003712 // In case we run without an image there won't be a backing oat file.
3713 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003714 return false;
3715 }
3716
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003717 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003718 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003719 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3720 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003721 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003722 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003723 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003724 // Compile time verification failed with a soft error. Compile time verification can fail
3725 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003726 // class ... {
3727 // Foo x;
3728 // .... () {
3729 // if (...) {
3730 // v1 gets assigned a type of resolved class Foo
3731 // } else {
3732 // v1 gets assigned a type of unresolved class Bar
3733 // }
3734 // iput x = v1
3735 // } }
3736 // when we merge v1 following the if-the-else it results in Conflict
3737 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3738 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3739 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3740 // at compile time).
3741 return false;
3742 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003743 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003744 // Compile time verification failed with a hard error. This is caused by invalid instructions
3745 // in the class. These errors are unrecoverable.
3746 return false;
3747 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003748 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003749 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3750 // not loading the class.
3751 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3752 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003753 return false;
3754 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003755 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003756 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003757 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003758 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003759
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003760 return false;
3761}
3762
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003763void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003764 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003765 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3766 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3767 }
3768 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3769 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3770 }
3771}
3772
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003773void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003774 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003775 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3776 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003777 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003778 return; // native or abstract method
3779 }
3780 if (code_item->tries_size_ == 0) {
3781 return; // nothing to process
3782 }
3783 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
3784 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3785 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3786 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3787 CatchHandlerIterator iterator(handlers_ptr);
3788 for (; iterator.HasNext(); iterator.Next()) {
3789 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3790 // unresolved exception types will be ignored by exception delivery
3791 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003792 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003793 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003794 DCHECK(Thread::Current()->IsExceptionPending());
3795 Thread::Current()->ClearException();
3796 }
3797 }
3798 }
3799 handlers_ptr = iterator.EndDataPointer();
3800 }
3801}
3802
Brian Carlstromea46f952013-07-30 01:26:50 -07003803static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003804static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3805 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003806
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003807mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003808 jobjectArray interfaces, jobject loader,
3809 jobjectArray methods, jobjectArray throws) {
3810 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003811 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003812 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003813 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003814 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003815 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003816 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003817 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003818 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003819 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003820 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3821 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003822 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003823 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003824 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003825 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003826 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003827 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003828
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003829 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003830 {
3831 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003832 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003833 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003834 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003835 }
3836 klass->SetSFields(sfields);
3837 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003838 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3839 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003840 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3841 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003842 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003843 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003844 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003845 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003846 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003847 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003848 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3849 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003850 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3851 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003852 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003853 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003854 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003855 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003856 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003857 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003858 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003859
Ian Rogers466bb252011-10-14 03:29:56 -07003860 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003861 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003862 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003863 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003864 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003865 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003866 }
3867 klass->SetDirectMethods(directs);
3868 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003869 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003870 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003871 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003872 }
3873 klass->SetDirectMethod(0, constructor);
3874 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003875
Mathieu Chartier590fee92013-09-13 13:46:47 -07003876 // Create virtual method using specified prototypes.
3877 size_t num_virtual_methods =
3878 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003879 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003880 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3881 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003882 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003883 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003884 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003885 }
3886 klass->SetVirtualMethods(virtuals);
3887 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003888 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003889 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003890 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3891 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003892 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003893 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003894 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003895 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003896 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003897 }
3898 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003899 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003900
3901 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003902 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003903 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003904
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003905 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3906 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003907 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003908 // Must hold lock on object when resolved.
3909 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003910 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003911 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003912 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003913 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003914 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003915 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003916 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003917 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003918
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003919 CHECK(klass->IsRetired());
3920 CHECK_NE(klass.Get(), new_class);
3921 klass.Assign(new_class);
3922
3923 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003924 interfaces_sfield->SetObject<false>(klass.Get(),
3925 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003926 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003927 throws_sfield->SetObject<false>(klass.Get(),
3928 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003929
3930 {
3931 // Lock on klass is released. Lock new class object.
3932 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003933 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003934 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003935
3936 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003937 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003938 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003939 CheckProxyConstructor(klass->GetDirectMethod(0));
3940 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003941 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003942 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3943 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003944 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003945 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3946 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003947 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003948
Mathieu Chartier590fee92013-09-13 13:46:47 -07003949 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003950 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003951 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003952 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3953
3954 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003955 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003956 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003957
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003958 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003959 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003960 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003961 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003962 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003963 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003964 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003965 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003966}
3967
Ian Rogersef7d42f2014-01-06 12:55:46 -08003968std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003969 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003970 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003971 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003972 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3973}
3974
Ian Rogersef7d42f2014-01-06 12:55:46 -08003975mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3976 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003977 DCHECK(proxy_class->IsProxyClass());
3978 DCHECK(proxy_method->IsProxyMethod());
3979 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003980 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003981 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003982 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003983 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003984 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003985 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003986 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003987 break;
3988 }
3989 }
3990 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003991 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003992 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003993 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003994 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003995 return resolved_method;
3996}
3997
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003998
Brian Carlstromea46f952013-07-30 01:26:50 -07003999mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004000 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07004001 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07004002 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07004003 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004004 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07004005 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
4006 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02004007 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4008 // constructor method.
4009 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
4010 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07004011 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4012 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07004013 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
4014 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004015 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07004016 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004017 }
Ian Rogers466bb252011-10-14 03:29:56 -07004018 // Make this constructor public and fix the class to be our Proxy version
4019 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004020 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004021 return constructor;
4022}
4023
Brian Carlstromea46f952013-07-30 01:26:50 -07004024static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004025 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004026 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004027 CHECK_STREQ(constructor->GetName(), "<init>");
4028 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4029 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004030 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004031}
4032
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004033mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004034 Handle<mirror::Class> klass,
4035 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004036 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4037 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004038 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004039 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004040 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004041 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004042 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004043 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004044 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004045 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004046 }
Ian Rogers466bb252011-10-14 03:29:56 -07004047
4048 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4049 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004050 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004051 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004052
Ian Rogers466bb252011-10-14 03:29:56 -07004053 // At runtime the method looks like a reference and argument saving method, clone the code
4054 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004055 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4056 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004057 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004058
Ian Rogersc2b44472011-12-14 21:17:17 -08004059 return method;
4060}
Jesse Wilson95caa792011-10-12 18:14:17 -04004061
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004062static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4063 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004064 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004065 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004066 CHECK(!prototype->IsFinal());
4067 CHECK(method->IsFinal());
4068 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004069
4070 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4071 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4072 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004073 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4074 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004075 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4076
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004077 StackHandleScope<2> hs(Thread::Current());
4078 MethodHelper mh(hs.NewHandle(method.Get()));
4079 MethodHelper mh2(hs.NewHandle(prototype.Get()));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004080 CHECK_STREQ(method->GetName(), prototype->GetName());
4081 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004082 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08004083 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004084}
4085
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004086static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4087 bool can_init_parents)
4088 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004089 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004090 return true;
4091 }
4092 if (!can_init_statics) {
4093 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004094 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004095 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004096 return false;
4097 }
4098 // Check if there are encoded static values needing initialization.
4099 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004100 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004101 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004102 if (dex_class_def->static_values_off_ != 0) {
4103 return false;
4104 }
4105 }
4106 }
4107 if (!klass->IsInterface() && klass->HasSuperClass()) {
4108 mirror::Class* super_class = klass->GetSuperClass();
4109 if (!can_init_parents && !super_class->IsInitialized()) {
4110 return false;
4111 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004112 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004113 return false;
4114 }
4115 }
4116 }
4117 return true;
4118}
4119
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004120bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004121 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004122 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4123
4124 // Are we already initialized and therefore done?
4125 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4126 // an initialized class will never change its state.
4127 if (klass->IsInitialized()) {
4128 return true;
4129 }
4130
4131 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004132 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004133 return false;
4134 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004135
Ian Rogers7b078e82014-09-10 14:44:24 -07004136 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004137 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004138 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004139 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004140
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004141 // Re-check under the lock in case another thread initialized ahead of us.
4142 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004143 return true;
4144 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004145
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004146 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004147 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004148 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004149 return false;
4150 }
4151
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004152 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004153
4154 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004155 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004156 if (!klass->IsVerified()) {
4157 // We failed to verify, expect either the klass to be erroneous or verification failed at
4158 // compile time.
4159 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004160 CHECK(self->IsExceptionPending());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004161 } else {
4162 CHECK(Runtime::Current()->IsCompiler());
4163 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004164 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004165 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004166 } else {
4167 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004168 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004169 }
4170
Brian Carlstromd1422f82011-09-28 11:37:09 -07004171 // If the class is kStatusInitializing, either this thread is
4172 // initializing higher up the stack or another thread has beat us
4173 // to initializing and we need to wait. Either way, this
4174 // invocation of InitializeClass will not be responsible for
4175 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004176 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004177 // Could have got an exception during verification.
4178 if (self->IsExceptionPending()) {
4179 return false;
4180 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004181 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004182 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004183 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004184 return true;
4185 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004186 // No. That's fine. Wait for another thread to finish initializing.
4187 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004188 }
4189
4190 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004191 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004192 return false;
4193 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004194 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004195
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004196 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004197
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004198 // From here out other threads may observe that we're initializing and so changes of state
4199 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004200 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004201 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004202
4203 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004204 }
4205
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004206 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004207 if (!klass->IsInterface() && klass->HasSuperClass()) {
4208 mirror::Class* super_class = klass->GetSuperClass();
4209 if (!super_class->IsInitialized()) {
4210 CHECK(!super_class->IsInterface());
4211 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004212 StackHandleScope<1> hs(self);
4213 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004214 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004215 if (!super_initialized) {
4216 // The super class was verified ahead of entering initializing, we should only be here if
4217 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004218 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004219 << "Super class initialization failed for "
4220 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004221 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004222 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004223 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004224 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004225 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004226 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004227 return false;
4228 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004229 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004230 }
4231
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004232 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004233 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004234 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004235 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004236 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004237 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004238 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004239 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4240 this, *dex_class_def);
4241 const byte* class_data = dex_file.GetClassData(*dex_class_def);
4242 ClassDataItemIterator field_it(dex_file, class_data);
4243 if (value_it.HasNext()) {
4244 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004245 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004246 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004247 StackHandleScope<1> hs(self);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004248 Handle<mirror::ArtField> field(hs.NewHandle(
4249 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004250 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004251 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004252 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004253 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004254 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004255 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004256 }
4257 }
4258 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004259
Ian Rogersd91d6d62013-09-25 20:26:14 -07004260 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004261 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004262 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004263 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004264 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004265 }
4266
Ian Rogers7b078e82014-09-10 14:44:24 -07004267 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004268 uint64_t t1 = NanoTime();
4269
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004270 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004271 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004272 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004273
4274 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07004275 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004276 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004277 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004278 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004279 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4280 RuntimeStats* thread_stats = self->GetStats();
4281 ++global_stats->class_init_count;
4282 ++thread_stats->class_init_count;
4283 global_stats->class_init_time_ns += (t1 - t0);
4284 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004285 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004286 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004287 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004288 std::string temp;
4289 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004290 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004291 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004292 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004293 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004294 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004295 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004296 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004297}
4298
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004299bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004300 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004301 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004302 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004303 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004304 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004305 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004306
4307 // When we wake up, repeat the test for init-in-progress. If
4308 // there's an exception pending (only possible if
4309 // "interruptShouldThrow" was set), bail out.
4310 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07004311 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004312 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004313 return false;
4314 }
4315 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004316 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004317 continue;
4318 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004319 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004320 // Compile time initialization failed.
4321 return false;
4322 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004323 if (klass->IsErroneous()) {
4324 // The caller wants an exception, but it was thrown in a
4325 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004326 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004327 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004328 return false;
4329 }
4330 if (klass->IsInitialized()) {
4331 return true;
4332 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004333 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004334 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004335 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004336 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004337}
4338
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004339bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004340 if (klass->IsInterface()) {
4341 return true;
4342 }
Ian Rogers151f2212014-05-06 11:27:27 -07004343 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004344 StackHandleScope<2> hs(Thread::Current());
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004345 MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4346 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004347 if (klass->HasSuperClass() &&
4348 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004349 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4350 mh.ChangeMethod(klass->GetVTableEntry(i));
4351 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004352 if (mh.GetMethod() != super_mh.GetMethod() &&
4353 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4354 ThrowLinkageError(klass.Get(),
4355 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004356 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004357 PrettyMethod(mh.GetMethod()).c_str(),
4358 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004359 return false;
4360 }
4361 }
4362 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004363 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004364 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4365 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4366 for (uint32_t j = 0; j < num_methods; ++j) {
4367 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4368 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004369 if (mh.GetMethod() != super_mh.GetMethod() &&
4370 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4371 ThrowLinkageError(klass.Get(),
4372 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004373 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004374 PrettyMethod(mh.GetMethod()).c_str(),
4375 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004376 return false;
4377 }
4378 }
4379 }
4380 }
4381 return true;
4382}
4383
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004384bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4385 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004386 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004387 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004388 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004389 return true;
4390 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004391 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004392 if (!success) {
4393 if (can_init_fields && can_init_parents) {
4394 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4395 }
4396 } else {
4397 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004398 }
4399 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004400}
4401
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004402void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4403 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4404 if (fields != nullptr) {
4405 for (int index = 0; index < fields->GetLength(); index ++) {
4406 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4407 fields->Get(index)->SetDeclaringClass(new_class);
4408 }
4409 }
4410 }
4411
4412 fields = new_class->GetSFields();
4413 if (fields != nullptr) {
4414 for (int index = 0; index < fields->GetLength(); index ++) {
4415 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4416 fields->Get(index)->SetDeclaringClass(new_class);
4417 }
4418 }
4419 }
4420
4421 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4422 if (methods != nullptr) {
4423 for (int index = 0; index < methods->GetLength(); index ++) {
4424 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4425 methods->Get(index)->SetDeclaringClass(new_class);
4426 }
4427 }
4428 }
4429
4430 methods = new_class->GetVirtualMethods();
4431 if (methods != nullptr) {
4432 for (int index = 0; index < methods->GetLength(); index ++) {
4433 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4434 methods->Get(index)->SetDeclaringClass(new_class);
4435 }
4436 }
4437 }
4438}
4439
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004440bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4441 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004442 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004443 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004444
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004445 if (!LinkSuperClass(klass)) {
4446 return false;
4447 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004448 if (!LinkMethods(self, klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004449 return false;
4450 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004451 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004452 return false;
4453 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004454 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004455 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004456 return false;
4457 }
4458 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004459 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004460
4461 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4462 // We don't need to retire this class as it has no embedded tables or it was created the
4463 // correct size during class linker initialization.
4464 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4465
4466 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4467 klass->PopulateEmbeddedImtAndVTable();
4468 }
4469
4470 // This will notify waiters on klass that saw the not yet resolved
4471 // class in the class_table_ during EnsureResolved.
4472 klass->SetStatus(mirror::Class::kStatusResolved, self);
4473 *new_class = klass.Get();
4474 } else {
4475 CHECK(!klass->IsResolved());
4476 // Retire the temporary class and create the correctly sized resolved class.
4477 *new_class = klass->CopyOf(self, class_size);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004478 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004479 CHECK(self->IsExceptionPending()); // Expect an OOME.
4480 klass->SetStatus(mirror::Class::kStatusError, self);
4481 return false;
4482 }
4483
4484 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4485 StackHandleScope<1> hs(self);
4486 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4487 ObjectLock<mirror::Class> lock(self, new_class_h);
4488
4489 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4490
4491 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004492 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004493
4494 // This will notify waiters on temp class that saw the not yet resolved class in the
4495 // class_table_ during EnsureResolved.
4496 klass->SetStatus(mirror::Class::kStatusRetired, self);
4497
4498 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4499 // This will notify waiters on new_class that saw the not yet resolved
4500 // class in the class_table_ during EnsureResolved.
4501 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004502 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004503 return true;
4504}
4505
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004506bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004507 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004508 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4509 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004510 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004511 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004512 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004513 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004514 return false;
4515 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004516 // Verify
4517 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004518 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004519 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004520 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004521 return false;
4522 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004523 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004524 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004525 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004526 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004527 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004528 for (size_t i = 0; i < interfaces->Size(); i++) {
4529 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004530 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004531 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004532 DCHECK(Thread::Current()->IsExceptionPending());
4533 return false;
4534 }
4535 // Verify
4536 if (!klass->CanAccess(interface)) {
4537 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004538 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004539 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004540 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004541 return false;
4542 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004543 }
4544 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004545 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004546 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004547 return true;
4548}
4549
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004550bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004551 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004552 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004553 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004554 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004555 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004556 return false;
4557 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004558 return true;
4559 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004560 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004561 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4562 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004563 return false;
4564 }
4565 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004566 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004567 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004568 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004569 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004570 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004571 return false;
4572 }
4573 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004574 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004575 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004576 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004577 return false;
4578 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004579
Brian Carlstromf3632832014-05-20 15:36:53 -07004580 // Inherit kAccClassIsFinalizable from the superclass in case this
4581 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004582 if (super->IsFinalizable()) {
4583 klass->SetFinalizable();
4584 }
4585
Elliott Hughes2da50362011-10-10 16:57:08 -07004586 // Inherit reference flags (if any) from the superclass.
4587 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4588 if (reference_flags != 0) {
4589 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4590 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004591 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004592 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004593 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004594 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004595 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004596 return false;
4597 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004598
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004599 if (kIsDebugBuild) {
4600 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004601 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004602 CHECK(super->IsResolved());
4603 super = super->GetSuperClass();
4604 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004605 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004606 return true;
4607}
4608
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004609// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004610bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
4611 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004612 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004613 if (klass->IsInterface()) {
4614 // No vtable.
4615 size_t count = klass->NumVirtualMethods();
4616 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004617 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004618 return false;
4619 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004620 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004621 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004622 }
jeffhaobdb76512011-09-07 11:43:16 -07004623 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004624 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004625 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07004626 // Link virtual and interface method tables
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004627 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004628 }
4629 return true;
4630}
4631
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004632bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004633 if (klass->HasSuperClass()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004634 uint32_t max_count = klass->NumVirtualMethods() +
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004635 klass->GetSuperClass()->GetVTableLength();
4636 size_t actual_count = klass->GetSuperClass()->GetVTableLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004637 CHECK_LE(actual_count, max_count);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004638 StackHandleScope<4> hs(self);
4639 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004640 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004641 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4642 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4643 if (UNLIKELY(vtable.Get() == nullptr)) {
4644 CHECK(self->IsExceptionPending()); // OOME.
4645 return false;
4646 }
4647 int len = super_class->GetVTableLength();
Mingyao Yang1a128582014-07-22 17:33:25 -07004648 for (int i = 0; i < len; i++) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004649 vtable->Set<false>(i, super_class->GetVTableEntry(i));
4650 }
4651 } else {
Mingyao Yang38eecb02014-08-13 14:51:03 -07004652 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004653 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4654 if (UNLIKELY(vtable.Get() == nullptr)) {
4655 CHECK(self->IsExceptionPending()); // OOME.
4656 return false;
4657 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004658 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004659
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004660 // See if any of our virtual methods override the superclass.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004661 MutableMethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4662 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004663 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004664 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004665 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004666 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004667 for (; j < actual_count; ++j) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004668 mirror::ArtMethod* super_method = vtable->Get(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004669 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004670 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004671 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4672 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004673 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004674 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004675 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004676 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004677 return false;
4678 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004679 vtable->Set<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004680 local_method->SetMethodIndex(j);
4681 break;
4682 } else {
4683 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4684 << " would have incorrectly overridden the package-private method in "
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004685 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004686 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004687 }
4688 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004689 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004690 // Not overriding, append.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004691 vtable->Set<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004692 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004693 actual_count += 1;
4694 }
4695 }
4696 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004697 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004698 return false;
4699 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004700 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004701 CHECK_LE(actual_count, max_count);
4702 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004703 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004704 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004705 CHECK(self->IsExceptionPending()); // OOME.
4706 return false;
4707 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004708 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004709 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004710 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004711 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004712 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004713 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004714 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004715 return false;
4716 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004717 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004718 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004719 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004720 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004721 CHECK(self->IsExceptionPending()); // OOME.
4722 return false;
4723 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004724 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004725 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004726 vtable->Set<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004727 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004728 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004729 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004730 }
4731 return true;
4732}
4733
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004734bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass,
4735 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004736 Thread* const self = Thread::Current();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004737 Runtime* const runtime = Runtime::Current();
Jeff Hao88474b42013-10-23 16:24:40 -07004738 // Set the imt table to be all conflicts by default.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004739 klass->SetImTable(runtime->GetDefaultImt());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004740 size_t super_ifcount;
4741 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004742 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004743 } else {
4744 super_ifcount = 0;
4745 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07004746 uint32_t num_interfaces =
4747 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4748 size_t ifcount = super_ifcount + num_interfaces;
4749 for (size_t i = 0; i < num_interfaces; i++) {
4750 mirror::Class* interface =
4751 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4752 interfaces->Get(i);
4753 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004754 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004755 if (ifcount == 0) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004756 // Class implements no interfaces.
4757 DCHECK_EQ(klass->GetIfTableCount(), 0);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004758 DCHECK(klass->GetIfTable() == nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004759 return true;
4760 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004761 if (ifcount == super_ifcount) {
4762 // Class implements same interfaces as parent, are any of these not marker interfaces?
4763 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004764 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Ian Rogers9bc81912012-10-11 21:43:36 -07004765 for (size_t i = 0; i < ifcount; ++i) {
4766 if (super_iftable->GetMethodArrayCount(i) > 0) {
4767 has_non_marker_interface = true;
4768 break;
4769 }
4770 }
4771 if (!has_non_marker_interface) {
4772 // Class just inherits marker interfaces from parent so recycle parent's iftable.
4773 klass->SetIfTable(super_iftable);
4774 return true;
4775 }
4776 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004777 StackHandleScope<5> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004778 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004779 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004780 CHECK(self->IsExceptionPending()); // OOME.
4781 return false;
4782 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004783 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004784 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004785 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004786 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004787 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004788 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004789 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004790 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004791 // Flatten the interface inheritance hierarchy.
4792 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004793 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004794 mirror::Class* interface =
Mathieu Chartierf8322842014-05-16 10:59:25 -07004795 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4796 interfaces->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004797 DCHECK(interface != nullptr);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004798 if (!interface->IsInterface()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004799 std::string temp;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004800 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4801 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers1ff3c982014-08-12 02:30:58 -07004802 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004803 return false;
4804 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004805 // Check if interface is already in iftable
4806 bool duplicate = false;
4807 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004808 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004809 if (existing_interface == interface) {
4810 duplicate = true;
4811 break;
4812 }
4813 }
4814 if (!duplicate) {
4815 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004816 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004817 // Add this interface's non-duplicate super-interfaces.
4818 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004819 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004820 bool super_duplicate = false;
4821 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004822 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004823 if (existing_interface == super_interface) {
4824 super_duplicate = true;
4825 break;
4826 }
4827 }
4828 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004829 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004830 }
4831 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004832 }
4833 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004834 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004835 // Shrink iftable in case duplicates were found
4836 if (idx < ifcount) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004837 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004838 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004839 CHECK(self->IsExceptionPending()); // OOME.
4840 return false;
4841 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004842 ifcount = idx;
4843 } else {
4844 CHECK_EQ(idx, ifcount);
4845 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004846 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004847
4848 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004849 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004850 return true;
4851 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004852 self->AllowThreadSuspension();
Jeff Hao88474b42013-10-23 16:24:40 -07004853 // Allocate imtable
4854 bool imtable_changed = false;
Ian Rogers700a4022014-05-19 16:49:03 -07004855 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004856 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004857 if (UNLIKELY(imtable.Get() == nullptr)) {
Jeff Hao88474b42013-10-23 16:24:40 -07004858 CHECK(self->IsExceptionPending()); // OOME.
4859 return false;
4860 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004861 MutableMethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4862 MutableMethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004863 size_t max_miranda_methods = 0; // The max size of miranda_list.
4864 for (size_t i = 0; i < ifcount; ++i) {
4865 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4866 }
4867 Handle<mirror::ObjectArray<mirror::ArtMethod>>
4868 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
4869 size_t miranda_list_size = 0; // The current size of miranda_list.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004870 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004871 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004872 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004873 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004874 StackHandleScope<2> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004875 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004876 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4877 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004878 CHECK(self->IsExceptionPending()); // OOME.
4879 return false;
4880 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004881 iftable->SetMethodArray(i, method_array.Get());
Ian Rogers700a4022014-05-19 16:49:03 -07004882 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004883 hs.NewHandle(klass->GetVTableDuringLinking()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004884 for (size_t j = 0; j < num_methods; ++j) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004885 interface_mh.ChangeMethod(iftable->GetInterface(i)->GetVirtualMethod(j));
Ian Rogers9bc81912012-10-11 21:43:36 -07004886 int32_t k;
4887 // For each method listed in the interface's method list, find the
4888 // matching method in our class's method list. We want to favor the
4889 // subclass over the superclass, which just requires walking
4890 // back from the end of the vtable. (This only matters if the
4891 // superclass defines a private method and this class redefines
4892 // it -- otherwise it would use the same vtable slot. In .dex files
4893 // those don't end up in the virtual method table, so it shouldn't
4894 // matter which direction we go. We walk it backward anyway.)
4895 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004896 vtable_mh.ChangeMethod(vtable->Get(k));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004897 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004898 if (!vtable_mh.Get()->IsAbstract() && !vtable_mh.Get()->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004899 ThrowIllegalAccessError(
4900 klass.Get(),
4901 "Method '%s' implementing interface method '%s' is not public",
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004902 PrettyMethod(vtable_mh.Get()).c_str(),
4903 PrettyMethod(interface_mh.Get()).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004904 return false;
4905 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004906 method_array->Set<false>(j, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004907 // Place method in imt if entry is empty, place conflict otherwise.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004908 uint32_t imt_index = interface_mh.Get()->GetDexMethodIndex() % mirror::Class::kImtSize;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004909 if (imtable->Get(imt_index) == nullptr) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004910 imtable->Set<false>(imt_index, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004911 imtable_changed = true;
4912 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004913 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -07004914 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004915 break;
4916 }
4917 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004918 if (k < 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004919 StackHandleScope<1> hs(self);
4920 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004921 for (size_t l = 0; l < miranda_list_size; ++l) {
4922 mirror::ArtMethod* mir_method = miranda_list->Get(l);
4923 DCHECK(mir_method != nullptr);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004924 vtable_mh.ChangeMethod(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004925 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004926 miranda_method.Assign(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004927 break;
4928 }
4929 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004930 if (miranda_method.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004931 // Point the interface table at a phantom slot.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004932 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_mh.Get()->Clone(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004933 if (UNLIKELY(miranda_method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004934 CHECK(self->IsExceptionPending()); // OOME.
4935 return false;
4936 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004937 DCHECK_LT(miranda_list_size, max_miranda_methods);
4938 miranda_list->Set<false>(miranda_list_size++, miranda_method.Get());
Ian Rogers9bc81912012-10-11 21:43:36 -07004939 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004940 method_array->Set<false>(j, miranda_method.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004941 }
4942 }
4943 }
4944 }
Jeff Hao88474b42013-10-23 16:24:40 -07004945 if (imtable_changed) {
4946 // Fill in empty entries in interface method table with conflict.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004947 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004948 for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004949 if (imtable->Get(i) == nullptr) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004950 imtable->Set<false>(i, imt_conflict_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004951 }
4952 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004953 klass->SetImTable(imtable.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004954 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004955 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004956 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004957 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004958 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4959 if (old_method_count == 0) {
4960 virtuals = AllocArtMethodArray(self, new_method_count);
4961 } else {
4962 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4963 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004964 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004965 CHECK(self->IsExceptionPending()); // OOME.
4966 return false;
4967 }
4968 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004969
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004970 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004971 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004972 hs.NewHandle(klass->GetVTableDuringLinking()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004973 CHECK(vtable.Get() != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004974 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004975 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004976 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004977 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004978 CHECK(self->IsExceptionPending()); // OOME.
4979 return false;
4980 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004981 for (size_t i = 0; i < miranda_list_size; ++i) {
4982 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004983 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004984 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4985 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4986 klass->SetVirtualMethod(old_method_count + i, method);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004987 vtable->Set<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004988 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004989 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004990 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004991 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004992
Brian Carlstromea46f952013-07-30 01:26:50 -07004993 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07004994 for (int i = 0; i < vtable->GetLength(); ++i) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004995 CHECK(vtable->Get(i) != nullptr);
Elliott Hughes4681c802011-09-25 18:04:37 -07004996 }
4997
Ian Rogers7b078e82014-09-10 14:44:24 -07004998 self->AllowThreadSuspension();
Elliott Hughes4681c802011-09-25 18:04:37 -07004999
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005000 return true;
5001}
5002
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005003bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005004 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005005 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005006}
5007
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005008bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005009 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005010 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005011}
5012
Brian Carlstromdbc05252011-09-09 01:59:59 -07005013struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005014 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5015 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005016 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005017 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005018 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005019 // 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 -07005020 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5021 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005022 if (type1 != type2) {
5023 bool is_primitive1 = type1 != Primitive::kPrimNot;
5024 bool is_primitive2 = type2 != Primitive::kPrimNot;
Fred Shih37f05ef2014-07-16 18:38:08 -07005025 if (type1 != type2) {
5026 if (is_primitive1 && is_primitive2) {
5027 // Larger primitive types go first.
5028 return Primitive::ComponentSize(type1) > Primitive::ComponentSize(type2);
5029 } else {
5030 // Reference always goes first.
5031 return !is_primitive1;
5032 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08005033 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005034 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005035 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005036 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005037 }
5038};
5039
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005040bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005041 size_t* class_size) {
5042 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005043 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005044 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005045
Brian Carlstromea46f952013-07-30 01:26:50 -07005046 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005047 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005048
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005049 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005050 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005051 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005052 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
5053 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
5054 // Static fields come after the embedded tables.
5055 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
Fred Shih37f05ef2014-07-16 18:38:08 -07005056 0, 0, 0, 0, 0);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005057 }
5058 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005059 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005060 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005061 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005062 CHECK(super_class->IsResolved())
5063 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005064 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005065 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005066 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005067
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005068 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005069
Brian Carlstromdbc05252011-09-09 01:59:59 -07005070 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005071 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005072 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005073 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005074 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005075 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005076 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005077 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005078 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005079 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005080 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5081 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005082
Fred Shih381e4ca2014-08-25 17:24:27 -07005083 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005084 size_t current_field = 0;
5085 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005086 FieldGaps gaps;
5087
Brian Carlstromdbc05252011-09-09 01:59:59 -07005088 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005089 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005090 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005091 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005092 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005093 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005094 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005095 if (UNLIKELY(!IsAligned<4>(field_offset.Uint32Value()))) {
5096 MemberOffset old_offset = field_offset;
5097 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5098 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5099 }
5100 DCHECK(IsAligned<4>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005101 grouped_and_sorted_fields.pop_front();
5102 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005103 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005104 field->SetOffset(field_offset);
5105 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005106 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005107 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5108 // otherwise we could end up with suboptimal gap fills.
5109 ShuffleForward<8>(num_fields, &current_field, &field_offset,
5110 fields, &grouped_and_sorted_fields, &gaps);
5111 ShuffleForward<4>(num_fields, &current_field, &field_offset,
5112 fields, &grouped_and_sorted_fields, &gaps);
5113 ShuffleForward<2>(num_fields, &current_field, &field_offset,
5114 fields, &grouped_and_sorted_fields, &gaps);
5115 ShuffleForward<1>(num_fields, &current_field, &field_offset,
5116 fields, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005117 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5118 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005119 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005120
Elliott Hughesadb460d2011-10-05 17:02:34 -07005121 // 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 -07005122 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005123 // We know there are no non-reference fields in the Reference classes, and we know
5124 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005125 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005126 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005127 --num_reference_fields;
5128 }
5129
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005130 if (kIsDebugBuild) {
5131 // Make sure that all reference fields appear before
5132 // non-reference fields, and all double-wide fields are aligned.
5133 bool seen_non_ref = false;
5134 for (size_t i = 0; i < num_fields; i++) {
5135 mirror::ArtField* field = fields->Get(i);
5136 if (false) { // enable to debug field layout
5137 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005138 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005139 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07005140 << " offset="
5141 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005142 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005143 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005144 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005145 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005146 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005147 is_primitive = true; // We lied above, so we have to expect a lie here.
5148 }
5149 if (is_primitive) {
5150 if (!seen_non_ref) {
5151 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07005152 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005153 }
5154 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07005155 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005156 }
5157 }
5158 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005159 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005160 }
5161 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005162
5163 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005164 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005165 if (is_static) {
5166 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005167 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005168 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005169 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005170 if (!klass->IsVariableSize()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005171 std::string temp;
5172 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005173 size_t previous_size = klass->GetObjectSize();
5174 if (previous_size != 0) {
5175 // Make sure that we didn't originally have an incorrect size.
Ian Rogers1ff3c982014-08-12 02:30:58 -07005176 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005177 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005178 klass->SetObjectSize(size);
5179 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005180 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005181 return true;
5182}
5183
5184// Set the bitmap of reference offsets, refOffsets, from the ifields
5185// list.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005186void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005187 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005188 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005189 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005190 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07005191 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005192 if (reference_offsets == CLASS_WALK_SUPER) {
5193 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005194 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005195 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005196 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005197 CreateReferenceOffsets(klass, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005198}
5199
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005200void ClassLinker::CreateReferenceOffsets(Handle<mirror::Class> klass,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005201 uint32_t reference_offsets) {
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005202 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
5203 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07005204 // All of the fields that contain object references are guaranteed
5205 // to be at the beginning of the fields list.
5206 for (size_t i = 0; i < num_reference_fields; ++i) {
5207 // Note that byte_offset is the offset from the beginning of
5208 // object, not the offset into instance data
Ian Rogersef7d42f2014-01-06 12:55:46 -08005209 mirror::ArtField* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005210 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005211 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
5212 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
5213 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07005214 CHECK_NE(new_bit, 0U);
5215 reference_offsets |= new_bit;
5216 } else {
5217 reference_offsets = CLASS_WALK_SUPER;
5218 break;
5219 }
5220 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005221 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005222}
5223
Mathieu Chartier590fee92013-09-13 13:46:47 -07005224mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005225 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005226 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005227 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005228 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005229 return resolved;
5230 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005231 uint32_t utf16_length;
5232 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005233 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005234 dex_cache->SetResolvedString(string_idx, string);
5235 return string;
5236}
5237
Mathieu Chartier590fee92013-09-13 13:46:47 -07005238mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005239 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005240 StackHandleScope<2> hs(Thread::Current());
5241 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5242 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005243 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5244}
5245
5246mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005247 Handle<mirror::DexCache> dex_cache,
5248 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005249 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005250 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005251 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005252 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005253 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005254 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005255 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005256 // TODO: we used to throw here if resolved's class loader was not the
5257 // boot class loader. This was to permit different classes with the
5258 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005259 dex_cache->SetResolvedType(type_idx, resolved);
5260 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005261 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005262 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005263 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005264 StackHandleScope<1> hs(self);
5265 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005266 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005267 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005268 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005269 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005270 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005271 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005272 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005273 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005274 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005275 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005276 return resolved;
5277}
5278
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005279mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005280 Handle<mirror::DexCache> dex_cache,
5281 Handle<mirror::ClassLoader> class_loader,
5282 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005283 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005284 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005285 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005286 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005287 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005288 return resolved;
5289 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005290 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005291 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005292 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005293 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005294 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005295 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005296 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005297 // Scan using method_idx, this saves string compares but will only hit for matching dex
5298 // caches/files.
5299 switch (type) {
5300 case kDirect: // Fall-through.
5301 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005302 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005303 break;
5304 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005305 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005306 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005307 break;
5308 case kSuper: // Fall-through.
5309 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005310 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005311 break;
5312 default:
5313 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005314 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005315 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005316 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005317 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005318 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005319 switch (type) {
5320 case kDirect: // Fall-through.
5321 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005322 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005323 break;
5324 case kInterface:
5325 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005326 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005327 break;
5328 case kSuper: // Fall-through.
5329 case kVirtual:
5330 resolved = klass->FindVirtualMethod(name, signature);
5331 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005332 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005333 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005334 // If we found a method, check for incompatible class changes.
5335 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005336 // Be a good citizen and update the dex cache to speed subsequent calls.
5337 dex_cache->SetResolvedMethod(method_idx, resolved);
5338 return resolved;
5339 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005340 // If we had a method, it's an incompatible-class-change error.
5341 if (resolved != nullptr) {
5342 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5343 } else {
5344 // We failed to find the method which means either an access error, an incompatible class
5345 // change, or no such method. First try to find the method among direct and virtual methods.
5346 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5347 const Signature signature = dex_file.GetMethodSignature(method_id);
5348 switch (type) {
5349 case kDirect:
5350 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005351 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005352 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5353 // have had a resolved method before, which triggers the "true" branch above.
5354 break;
5355 case kInterface:
5356 case kVirtual:
5357 case kSuper:
5358 resolved = klass->FindDirectMethod(name, signature);
5359 break;
5360 }
5361
5362 // If we found something, check that it can be accessed by the referrer.
5363 if (resolved != nullptr && referrer.Get() != nullptr) {
5364 mirror::Class* methods_class = resolved->GetDeclaringClass();
5365 mirror::Class* referring_class = referrer->GetDeclaringClass();
5366 if (!referring_class->CanAccess(methods_class)) {
5367 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5368 resolved, type);
5369 return nullptr;
5370 } else if (!referring_class->CanAccessMember(methods_class,
5371 resolved->GetAccessFlags())) {
5372 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5373 return nullptr;
5374 }
5375 }
5376
5377 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5378 // methods and throw if we find the method there. If we find nothing, throw a
5379 // NoSuchMethodError.
5380 switch (type) {
5381 case kDirect:
5382 case kStatic:
5383 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005384 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005385 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005386 resolved = klass->FindInterfaceMethod(name, signature);
5387 if (resolved != nullptr) {
5388 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5389 } else {
5390 ThrowNoSuchMethodError(type, klass, name, signature);
5391 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005392 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005393 break;
5394 case kInterface:
5395 if (resolved != nullptr) {
5396 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005397 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005398 resolved = klass->FindVirtualMethod(name, signature);
5399 if (resolved != nullptr) {
5400 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5401 } else {
5402 ThrowNoSuchMethodError(type, klass, name, signature);
5403 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005404 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005405 break;
5406 case kSuper:
Andreas Gampedf733752014-08-25 20:55:01 -07005407 if (resolved != nullptr) {
5408 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5409 } else {
5410 ThrowNoSuchMethodError(type, klass, name, signature);
5411 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005412 break;
5413 case kVirtual:
5414 if (resolved != nullptr) {
5415 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5416 } else {
5417 resolved = klass->FindInterfaceMethod(name, signature);
5418 if (resolved != nullptr) {
5419 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5420 } else {
5421 ThrowNoSuchMethodError(type, klass, name, signature);
5422 }
5423 }
5424 break;
5425 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005426 }
5427 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005428 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005429 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005430}
5431
Mathieu Chartier590fee92013-09-13 13:46:47 -07005432mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005433 Handle<mirror::DexCache> dex_cache,
5434 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005435 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005436 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005437 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005438 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005439 return resolved;
5440 }
5441 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005442 Thread* const self = Thread::Current();
5443 StackHandleScope<1> hs(self);
5444 Handle<mirror::Class> klass(
5445 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005446 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005447 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005448 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005449 }
5450
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005451 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005452 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005453 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005454 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005455 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005456
Andreas Gampe58a5af82014-07-31 16:23:49 -07005457 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005458 const char* name = dex_file.GetFieldName(field_id);
5459 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5460 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005461 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005462 } else {
5463 resolved = klass->FindInstanceField(name, type);
5464 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005465 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005466 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005467 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005468 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005469 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005470 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005471 return resolved;
5472}
5473
Brian Carlstromea46f952013-07-30 01:26:50 -07005474mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005475 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005476 Handle<mirror::DexCache> dex_cache,
5477 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005478 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005479 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005480 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005481 return resolved;
5482 }
5483 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005484 Thread* self = Thread::Current();
5485 StackHandleScope<1> hs(self);
5486 Handle<mirror::Class> klass(
5487 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005488 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005489 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005490 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005491 }
5492
Ian Rogersdfb325e2013-10-30 01:00:44 -07005493 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5494 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005495 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005496 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005497 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005498 dex_cache->SetResolvedField(field_idx, resolved);
5499 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005500 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005501 }
5502 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005503}
5504
Brian Carlstromea46f952013-07-30 01:26:50 -07005505const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005506 uint32_t* length) {
5507 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5508 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005509 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005510 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005511 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005512}
5513
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005514void ClassLinker::DumpAllClasses(int flags) {
5515 if (dex_cache_image_class_lookup_required_) {
5516 MoveImageClassesToClassTable();
5517 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005518 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5519 // 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 -08005520 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005521 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005522 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005523 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5524 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005525 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005526 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005527 }
5528
5529 for (size_t i = 0; i < all_classes.size(); ++i) {
5530 all_classes[i]->DumpClass(std::cerr, flags);
5531 }
5532}
5533
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005534void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005535 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005536 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005537 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005538 MoveImageClassesToClassTable();
5539 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005540 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005541 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005542}
5543
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005544size_t ClassLinker::NumLoadedClasses() {
5545 if (dex_cache_image_class_lookup_required_) {
5546 MoveImageClassesToClassTable();
5547 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005548 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005549 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005550}
5551
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005552pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005553 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005554}
5555
5556pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005557 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005558}
5559
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005560void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005561 DCHECK(!init_done_);
5562
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005563 DCHECK(klass != nullptr);
5564 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005565
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005566 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005567 DCHECK(class_roots != nullptr);
5568 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005569 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005570}
5571
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005572} // namespace art