blob: 9090f290fc982049b0c8328f06728878e707c4a8 [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());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700317 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800318 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800319 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700320
Elliott Hughes418d20f2011-09-22 14:00:39 -0700321 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700322 Handle<mirror::Class> class_array_class(hs.NewHandle(
323 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700324 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700325
Ian Rogers23435d02012-09-24 11:23:12 -0700326 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700327 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
328 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700329 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700330 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700331 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700332 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700333
Ian Rogers23435d02012-09-24 11:23:12 -0700334 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700335 Handle<mirror::Class> object_array_class(hs.NewHandle(
336 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700337 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700338
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700339 // Setup the char (primitive) class to be used for char[].
340 Handle<mirror::Class> char_class(hs.NewHandle(
341 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700342 // The primitive char class won't be initialized by
343 // InitializePrimitiveClass until line 459, but strings (and
344 // internal char arrays) will be allocated before that and the
345 // component size, which is computed from the primitive type, needs
346 // to be set here.
347 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700348
Ian Rogers23435d02012-09-24 11:23:12 -0700349 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700350 Handle<mirror::Class> char_array_class(hs.NewHandle(
351 AllocClass(self, java_lang_Class.Get(),
352 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700353 char_array_class->SetComponentType(char_class.Get());
354 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700355
Ian Rogers23435d02012-09-24 11:23:12 -0700356 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700357 Handle<mirror::Class> java_lang_String(hs.NewHandle(
358 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700359 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700360 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700361 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400362
Fred Shih4ee7a662014-07-11 09:59:27 -0700363 // Setup Reference.
364 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
365 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
366 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
367 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
368 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
369
Ian Rogers23435d02012-09-24 11:23:12 -0700370 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700371 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
372 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
373 kClassRootsMax));
374 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700375 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
376 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
377 SetClassRoot(kClassArrayClass, class_array_class.Get());
378 SetClassRoot(kObjectArrayClass, object_array_class.Get());
379 SetClassRoot(kCharArrayClass, char_array_class.Get());
380 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700381 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700382
383 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700384 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
385 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
386 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
387 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
388 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
389 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
390 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
391 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392
Ian Rogers23435d02012-09-24 11:23:12 -0700393 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700394 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700395
Ian Rogers23435d02012-09-24 11:23:12 -0700396 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700397 Handle<mirror::Class> int_array_class(hs.NewHandle(
398 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700399 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700400 mirror::IntArray::SetArrayClass(int_array_class.Get());
401 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700402
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700403 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700404
Ian Rogers52813c92012-10-11 11:50:38 -0700405 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700406 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
407 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700408 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700409 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700410 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411
Brian Carlstromf3632832014-05-20 15:36:53 -0700412 // Constructor, Field, Method, and AbstractMethod are necessary so
413 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700414 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
415 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700416 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700417 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700418 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700419 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700420 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700421
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700422 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
423 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700424 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700425 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700426 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700427 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700428
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700429 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700430
431 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700432 Handle<mirror::Class> object_array_string(hs.NewHandle(
433 AllocClass(self, java_lang_Class.Get(),
434 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700435 object_array_string->SetComponentType(java_lang_String.Get());
436 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700437
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700438 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
439 AllocClass(self, java_lang_Class.Get(),
440 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700441 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
442 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700443
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700444 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
445 AllocClass(self, java_lang_Class.Get(),
446 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700447 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
448 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700449
Ian Rogers23435d02012-09-24 11:23:12 -0700450 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
451 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
452 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700453 CHECK_NE(0U, boot_class_path.size());
454 for (size_t i = 0; i != boot_class_path.size(); ++i) {
455 const DexFile* dex_file = boot_class_path[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700456 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700457 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700458 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459
460 // now we can use FindSystemClass
461
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700462 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700463 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
464 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700465
Jeff Hao88474b42013-10-23 16:24:40 -0700466 // Create runtime resolution and imt conflict methods. Also setup the default imt.
467 Runtime* runtime = Runtime::Current();
468 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
469 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
470 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
471
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700472 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
473 // we do not need friend classes or a publicly exposed setter.
474 quick_generic_jni_trampoline_ = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
Alex Light64ad14d2014-08-19 14:23:13 -0700475 if (!runtime->IsCompiler()) {
476 // We need to set up the generic trampolines since we don't have an image.
477 quick_resolution_trampoline_ = reinterpret_cast<void*>(art_quick_resolution_trampoline);
478 quick_imt_conflict_trampoline_ = reinterpret_cast<void*>(art_quick_imt_conflict_trampoline);
479 quick_to_interpreter_bridge_trampoline_ = reinterpret_cast<void*>(art_quick_to_interpreter_bridge);
480 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700481
Mathieu Chartier66f19252012-09-18 08:57:04 -0700482 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700483 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800484 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700485 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700486 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700487 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800488 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700489 std::ostringstream os1, os2;
490 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
491 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
492 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
493 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700494 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800495 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700496 CHECK_EQ(java_lang_String.Get(), String_class);
497 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700498 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700499
Ian Rogers23435d02012-09-24 11:23:12 -0700500 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800501 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800502 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700503
Ian Rogers98379392014-02-24 16:53:16 -0800504 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800505 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700506
Ian Rogers98379392014-02-24 16:53:16 -0800507 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700508 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700509
Ian Rogers98379392014-02-24 16:53:16 -0800510 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800511 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700512
Ian Rogers98379392014-02-24 16:53:16 -0800513 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700514 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700515
Ian Rogers98379392014-02-24 16:53:16 -0800516 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800517 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700518
Ian Rogers98379392014-02-24 16:53:16 -0800519 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800520 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700521
Ian Rogers98379392014-02-24 16:53:16 -0800522 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800523 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700524
Ian Rogers98379392014-02-24 16:53:16 -0800525 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700526 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700527
Ian Rogers98379392014-02-24 16:53:16 -0800528 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700529 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700530
Ian Rogers23435d02012-09-24 11:23:12 -0700531 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800532 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700533 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800534 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700535 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700536 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
537 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700538 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700539 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700540 array_iftable->SetInterface(0, java_lang_Cloneable);
541 array_iftable->SetInterface(1, java_io_Serializable);
542 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700543
Ian Rogers23435d02012-09-24 11:23:12 -0700544 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700545 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
546 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
547 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
548 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700549 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700550 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800551 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700552 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700553
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700554 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800555 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700556 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700557
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700558 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800559 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700560 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700561
Brian Carlstromf3632832014-05-20 15:36:53 -0700562 mirror::Class* String_array_class =
563 FindSystemClass(self, class_roots_descriptors_[kJavaLangStringArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700564 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700565
Brian Carlstromea46f952013-07-30 01:26:50 -0700566 mirror::Class* Art_method_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800567 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700568 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700569
Brian Carlstromea46f952013-07-30 01:26:50 -0700570 mirror::Class* Art_field_array_class =
Ian Rogers98379392014-02-24 16:53:16 -0800571 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700572 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700573
Ian Rogers23435d02012-09-24 11:23:12 -0700574 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700575
Ian Rogers23435d02012-09-24 11:23:12 -0700576 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800577 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700578 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
579
Brian Carlstrom1f870082011-08-23 16:02:11 -0700580 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700581 // finish initializing Reference class
582 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
583 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
584 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
585 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
586 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700587 mirror::Class* java_lang_ref_FinalizerReference =
588 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700589 java_lang_ref_FinalizerReference->SetAccessFlags(
590 java_lang_ref_FinalizerReference->GetAccessFlags() |
591 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700592 mirror::Class* java_lang_ref_PhantomReference =
593 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700594 java_lang_ref_PhantomReference->SetAccessFlags(
595 java_lang_ref_PhantomReference->GetAccessFlags() |
596 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700597 mirror::Class* java_lang_ref_SoftReference =
598 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700599 java_lang_ref_SoftReference->SetAccessFlags(
600 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700601 mirror::Class* java_lang_ref_WeakReference =
602 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700603 java_lang_ref_WeakReference->SetAccessFlags(
604 java_lang_ref_WeakReference->GetAccessFlags() |
605 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700606
Ian Rogers23435d02012-09-24 11:23:12 -0700607 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800608 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700609 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700610 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
611
jeffhao8cd6dda2012-02-22 10:15:34 -0800612 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700613 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800614 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800615 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700616 SetClassRoot(kJavaLangClassNotFoundException,
617 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800618 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700619 SetClassRoot(kJavaLangStackTraceElementArrayClass,
620 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800621 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700622
Ian Rogers98379392014-02-24 16:53:16 -0800623 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700624
Brian Carlstroma004aa92012-02-08 18:05:09 -0800625 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700626}
627
Ian Rogers98379392014-02-24 16:53:16 -0800628void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800629 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700630
631 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700632 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700633 // as the types of the field can't be resolved prior to the runtime being
634 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800635 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700636 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800637 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800638
Brian Carlstromea46f952013-07-30 01:26:50 -0700639 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700640 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
641 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700642
Brian Carlstromea46f952013-07-30 01:26:50 -0700643 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700644 CHECK_STREQ(queue->GetName(), "queue");
645 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700646
Brian Carlstromea46f952013-07-30 01:26:50 -0700647 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700648 CHECK_STREQ(queueNext->GetName(), "queueNext");
649 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700650
Brian Carlstromea46f952013-07-30 01:26:50 -0700651 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700652 CHECK_STREQ(referent->GetName(), "referent");
653 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700654
Brian Carlstromea46f952013-07-30 01:26:50 -0700655 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700656 CHECK_STREQ(zombie->GetName(), "zombie");
657 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700658
Brian Carlstroma663ea52011-08-19 23:33:41 -0700659 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700660 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700661 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800662 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700663 CHECK(klass != nullptr);
664 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700665 // note SetClassRoot does additional validation.
666 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700667 }
668
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700669 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700670
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700671 // disable the slow paths in FindClass and CreatePrimitiveClass now
672 // that Object, Class, and Object[] are setup
673 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700674
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800675 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700676}
677
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700678void ClassLinker::RunRootClinits() {
679 Thread* self = Thread::Current();
680 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800681 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700682 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700683 StackHandleScope<1> hs(self);
684 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700685 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700686 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700687 }
688 }
689}
690
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700691bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800692 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000693 const char* oat_cache_filename,
694 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700695 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700696 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800697
Ian Rogers1d54e732013-05-02 21:10:01 -0700698 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800699 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700700 if (heap->GetImageSpace() == nullptr) {
701 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
702 // out of space anyway it might not matter.
703 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
704 "without an image.", dex_filename);
705 return false;
706 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700707 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800708
Brian Carlstrom6449c622014-02-10 23:48:36 -0800709 std::string dex_file_option("--dex-file=");
710 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800711
Brian Carlstrom6449c622014-02-10 23:48:36 -0800712 std::string oat_fd_option("--oat-fd=");
713 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800714
Brian Carlstrom6449c622014-02-10 23:48:36 -0800715 std::string oat_location_option("--oat-location=");
716 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800717
Brian Carlstrom6449c622014-02-10 23:48:36 -0800718 std::vector<std::string> argv;
719 argv.push_back(dex2oat);
720 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800721 argv.push_back("-classpath");
722 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800723 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800724
Ian Rogers8afeb852014-04-02 14:55:49 -0700725 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800726
Jeff Hao4a200f52014-04-01 14:58:49 -0700727 if (!Runtime::Current()->IsVerificationEnabled()) {
728 argv.push_back("--compiler-filter=verify-none");
729 }
730
Alex Light6e183f22014-07-18 14:57:04 -0700731 if (Runtime::Current()->MustRelocateIfPossible()) {
732 argv.push_back("--runtime-arg");
733 argv.push_back("-Xrelocate");
734 } else {
735 argv.push_back("--runtime-arg");
736 argv.push_back("-Xnorelocate");
737 }
738
Brian Carlstrom6449c622014-02-10 23:48:36 -0800739 if (!kIsTargetBuild) {
740 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700741 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700742
Brian Carlstrom6449c622014-02-10 23:48:36 -0800743 argv.push_back(boot_image_option);
744 argv.push_back(dex_file_option);
745 argv.push_back(oat_fd_option);
746 argv.push_back(oat_location_option);
747 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800748 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800749 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700750 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800751
752 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700753}
754
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700755const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700756 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800757 if (kIsDebugBuild) {
758 for (size_t i = 0; i < oat_files_.size(); ++i) {
759 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700760 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800761 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700762 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
763 oat_files_.push_back(oat_file);
764 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800765}
766
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700767OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
768 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700769 OatFile* oat_file = space->ReleaseOatFile();
770 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700771 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700772 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700773}
774
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100775const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800776 const char* dex_location = dex_file.GetLocation().c_str();
777 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100778 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800779}
780
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100781const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
782 const char* dex_location,
783 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700784 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100785 for (const OatFile* oat_file : oat_files_) {
786 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700787
788 if (oat_location != nullptr) {
789 if (oat_file->GetLocation() != oat_location) {
790 continue;
791 }
792 }
793
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700794 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800795 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700796 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100797 if (oat_dex_file != nullptr) {
798 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800799 }
800 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100801 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800802}
803
Calin Juravle621962a2014-09-02 15:53:55 +0100804
805// Loads all multi dex files from the given oat file returning true on success.
806//
807// Parameters:
808// oat_file - the oat file to load from
809// dex_location - the dex location used to generate the oat file
810// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
811// generated - whether or not the oat_file existed before or was just (re)generated
812// error_msgs - any error messages will be appended here
813// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
814static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
815 const char* dex_location,
816 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700817 bool generated,
818 std::vector<std::string>* error_msgs,
819 std::vector<const DexFile*>* dex_files) {
820 if (oat_file == nullptr) {
821 return false;
822 }
823
824 size_t old_size = dex_files->size(); // To rollback on error.
825
826 bool success = true;
827 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100828 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700829 const char* next_name = next_name_str.c_str();
830
Calin Juravle621962a2014-09-02 15:53:55 +0100831 uint32_t next_location_checksum;
832 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700833 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100834 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
835 // When i=0 the multidex name should be the same as the location name. We already have the
836 // checksum it so we don't need to recompute it.
837 if (dex_location_checksum == nullptr) {
838 next_location_checksum_pointer = nullptr;
839 } else {
840 next_location_checksum = *dex_location_checksum;
841 }
842 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700843 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100844 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700845 }
846
847 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
848
849 if (oat_dex_file == nullptr) {
850 if (i == 0 && generated) {
851 std::string error_msg;
852 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100853 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700854 oat_file->GetLocation().c_str());
855 error_msgs->push_back(error_msg);
856 }
857 break; // Not found, done.
858 }
859
860 // Checksum test. Test must succeed when generated.
861 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100862 if (next_location_checksum_pointer != nullptr) {
863 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700864 }
865
866 if (success) {
867 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
868 if (dex_file == nullptr) {
869 success = false;
870 error_msgs->push_back(error_msg);
871 } else {
872 dex_files->push_back(dex_file);
873 }
874 }
875
876 // When we generated the file, we expect success, or something is terribly wrong.
877 CHECK_EQ(false, generated && !success)
878 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100879 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700880 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
881 }
882
883 if (dex_files->size() == old_size) {
884 success = false; // We did not even find classes.dex
885 }
886
887 if (success) {
888 return true;
889 } else {
890 // Free all the dex files we have loaded.
891 auto it = dex_files->begin() + old_size;
892 auto it_end = dex_files->end();
893 for (; it != it_end; it++) {
894 delete *it;
895 }
896 dex_files->erase(dex_files->begin() + old_size, it_end);
897
898 return false;
899 }
900}
901
902// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
903// complicates the loading process, as we should not use an iterative loading process, because that
904// would register the oat file and dex files that come before the broken one. Instead, check all
905// multidex ahead of time.
906bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
907 std::vector<std::string>* error_msgs,
908 std::vector<const DexFile*>* dex_files) {
909 // 1) Check whether we have an open oat file.
910 // This requires a dex checksum, use the "primary" one.
911 uint32_t dex_location_checksum;
912 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
913 bool have_checksum = true;
914 std::string checksum_error_msg;
915 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100916 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700917 dex_location_checksum_pointer = nullptr;
918 have_checksum = false;
919 }
920
921 bool needs_registering = false;
922
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100923 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
924 dex_location_checksum_pointer);
925 std::unique_ptr<const OatFile> open_oat_file(
926 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700927
928 // 2) If we do not have an open one, maybe there's one on disk already.
929
930 // In case the oat file is not open, we play a locking game here so
931 // that if two different processes race to load and register or generate
932 // (or worse, one tries to open a partial generated file) we will be okay.
933 // This is actually common with apps that use DexClassLoader to work
934 // around the dex method reference limit and that have a background
935 // service running in a separate process.
936 ScopedFlock scoped_flock;
937
938 if (open_oat_file.get() == nullptr) {
939 if (oat_location != nullptr) {
940 // Can only do this if we have a checksum, else error.
941 if (!have_checksum) {
942 error_msgs->push_back(checksum_error_msg);
943 return false;
944 }
945
946 std::string error_msg;
947
948 // We are loading or creating one in the future. Time to set up the file lock.
949 if (!scoped_flock.Init(oat_location, &error_msg)) {
950 error_msgs->push_back(error_msg);
951 return false;
952 }
953
Alex Lighta59dd802014-07-02 16:28:08 -0700954 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700955 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
956 oat_location, &error_msg));
957
958 if (open_oat_file.get() == nullptr) {
959 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
960 dex_location, oat_location, error_msg.c_str());
961 VLOG(class_linker) << compound_msg;
962 error_msgs->push_back(compound_msg);
963 }
964 } else {
965 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100966 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700967 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
968 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100969 kRuntimeISA, error_msgs,
970 &obsolete_file_cleanup_failed));
971 // There's no point in going forward and eventually try to regenerate the
972 // file if we couldn't remove the obsolete one. Mostly likely we will fail
973 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100974 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
975 if (obsolete_file_cleanup_failed) {
976 return false;
977 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700978 }
979 needs_registering = true;
980 }
981
982 // 3) If we have an oat file, check all contained multidex files for our dex_location.
983 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100984 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
985 dex_location_checksum_pointer,
986 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700987 if (success) {
988 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
989 if (needs_registering) {
990 // We opened the oat file, so we must register it.
991 RegisterOatFile(oat_file);
992 }
Alex Light9dcc4572014-08-14 14:16:26 -0700993 // If the file isn't executable we failed patchoat but did manage to get the dex files.
994 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700995 } else {
996 if (needs_registering) {
997 // We opened it, delete it.
998 open_oat_file.reset();
999 } else {
1000 open_oat_file.release(); // Do not delete open oat files.
1001 }
1002 }
1003
1004 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
1005
1006 // Need a checksum, fail else.
1007 if (!have_checksum) {
1008 error_msgs->push_back(checksum_error_msg);
1009 return false;
1010 }
1011
1012 // Look in cache location if no oat_location is given.
1013 std::string cache_location;
1014 if (oat_location == nullptr) {
1015 // Use the dalvik cache.
1016 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
1017 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
1018 oat_location = cache_location.c_str();
1019 }
1020
Alex Light64ad14d2014-08-19 14:23:13 -07001021 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -07001022 // Definitely need to lock now.
1023 if (!scoped_flock.HasFile()) {
1024 std::string error_msg;
1025 if (!scoped_flock.Init(oat_location, &error_msg)) {
1026 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -07001027 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -07001028 }
1029 }
1030
Alex Light64ad14d2014-08-19 14:23:13 -07001031 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001032 // Create the oat file.
1033 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1034 oat_location, error_msgs));
1035 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001036
1037 // Failed, bail.
1038 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001039 std::string error_msg;
1040 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1041 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1042 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001043 return false;
1044 }
1045
1046 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001047 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1048 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001049 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001050 if (success) {
1051 RegisterOatFile(open_oat_file.release());
1052 return true;
1053 } else {
1054 return false;
1055 }
1056}
1057
1058const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1059 uint32_t dex_location_checksum,
1060 const char* oat_location,
1061 std::string* error_msg) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001062 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001063 !Runtime::Current()->IsCompiler(),
1064 error_msg));
1065 if (oat_file.get() == nullptr) {
1066 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1067 error_msg->c_str());
1068 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001069 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001070 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001071 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1072 if (image_space != nullptr) {
1073 const ImageHeader& image_header = image_space->GetImageHeader();
1074 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1075 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1076 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1077 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1078 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1079 actual_image_oat_checksum);
1080 return nullptr;
1081 }
1082
1083 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1084 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1085 if (expected_image_oat_offset != actual_image_oat_offset) {
1086 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1087 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1088 actual_image_oat_offset);
1089 return nullptr;
1090 }
1091 int32_t expected_patch_delta = image_header.GetPatchDelta();
1092 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1093 if (expected_patch_delta != actual_patch_delta) {
1094 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1095 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1096 return nullptr;
1097 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001098 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001099
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001100 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1101 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001102 if (oat_dex_file == nullptr) {
1103 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1104 dex_location);
1105 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001106 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001107 uint32_t expected_dex_checksum = dex_location_checksum;
1108 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1109 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001110 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1111 "found 0x%x", oat_location, expected_dex_checksum,
1112 actual_dex_checksum);
1113 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001114 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001115 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1116 if (dex_file.get() != nullptr) {
1117 return oat_file.release();
1118 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001119 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001120 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001121}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001122
Andreas Gampe833a4852014-05-21 18:46:59 -07001123const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1124 int fd, const char* oat_location,
1125 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001126 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001127 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001128 std::string error_msg;
1129 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001130 CHECK(!error_msg.empty());
1131 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001132 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001133 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001134 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001135 !Runtime::Current()->IsCompiler(),
1136 &error_msg));
1137 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001138 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1139 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001140 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001141 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001142 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001143
1144 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001145}
1146
Alex Light6e183f22014-07-18 14:57:04 -07001147bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1148 const InstructionSet instruction_set) {
1149 Runtime* runtime = Runtime::Current();
1150 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001151 if (image_space == nullptr) {
1152 return false;
1153 }
Alex Light6e183f22014-07-18 14:57:04 -07001154 uint32_t image_oat_checksum = 0;
1155 if (instruction_set == kRuntimeISA) {
1156 const ImageHeader& image_header = image_space->GetImageHeader();
1157 image_oat_checksum = image_header.GetOatChecksum();
1158 } else {
1159 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1160 image_space->GetImageLocation().c_str(), instruction_set));
1161 image_oat_checksum = image_header->GetOatChecksum();
1162 }
1163 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1164}
1165
1166bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1167 const InstructionSet instruction_set,
1168 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001169 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001170 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001171 if (image_space == nullptr) {
1172 *error_msg = "No image space for verification against";
1173 return false;
1174 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001175
1176 // If the requested instruction set is the same as the current runtime,
1177 // we can use the checksums directly. If it isn't, we'll have to read the
1178 // image header from the image for the right instruction set.
1179 uint32_t image_oat_checksum = 0;
1180 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001181 int32_t image_patch_delta = 0;
1182 if (instruction_set == Runtime::Current()->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001183 const ImageHeader& image_header = image_space->GetImageHeader();
1184 image_oat_checksum = image_header.GetOatChecksum();
1185 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001186 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001187 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001188 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001189 image_space->GetImageLocation().c_str(), instruction_set));
1190 image_oat_checksum = image_header->GetOatChecksum();
1191 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001192 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001193 }
1194 const OatHeader& oat_header = oat_file->GetOatHeader();
Alex Light6e183f22014-07-18 14:57:04 -07001195 bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1196 && (oat_header.GetImagePatchDelta() == image_patch_delta)
1197 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1198 if (!ret) {
1199 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1200 oat_file->GetLocation().c_str(),
1201 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1202 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1203 oat_file->GetOatHeader().GetImagePatchDelta(),
1204 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1205 }
1206 return ret;
1207}
1208
1209bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1210 const char* dex_location,
1211 uint32_t dex_location_checksum,
1212 const InstructionSet instruction_set,
1213 std::string* error_msg) {
1214 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1215 return false;
1216 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001217
Brian Carlstromf3632832014-05-20 15:36:53 -07001218 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1219 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001220 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001221 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1222 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001223 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1224 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001225 oat_file->GetLocation().c_str(),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001226 oat_dex_file->GetDexFileLocation().c_str(),
1227 oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001228 }
1229 return false;
1230 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001231
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001232 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001233 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001234}
1235
Alex Lighta59dd802014-07-02 16:28:08 -07001236bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1237 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001238 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001239 std::string* error_msg) {
1240 CHECK(oat_file != nullptr);
1241 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001242 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001243 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001244 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1245 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1246 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001247 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001248 if (oat_dex_file == nullptr) {
1249 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001250 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001251 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001252 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001253 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001254 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001255 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001256 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001257 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001258 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001259 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001260 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001261 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001262 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001263 }
Alex Lighta59dd802014-07-02 16:28:08 -07001264 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001265}
1266
Andreas Gampe833a4852014-05-21 18:46:59 -07001267const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001268 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001269 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001270 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001271 std::vector<std::string>* error_msgs,
1272 bool* obsolete_file_cleanup_failed) {
1273 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001274 bool already_opened = false;
1275 std::string dex_location_str(dex_location);
1276 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1277 &already_opened,
1278 obsolete_file_cleanup_failed,
1279 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001280 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001281 if (oat_file.get() == nullptr) {
1282 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1283 dex_location));
1284 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001285 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001286 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1287 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001288 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1289 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001290 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001291 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001292 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001293 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001294 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1295 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1296 "dex location '%s'. Image checksum incorrect.",
1297 oat_file->GetLocation().c_str(), dex_location));
1298 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001299 } else {
1300 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001301 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001302}
1303
Brian Carlstromae826982011-11-09 01:33:42 -08001304const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001305 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001306 for (size_t i = 0; i < oat_files_.size(); i++) {
1307 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001308 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001309 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001310 return oat_file;
1311 }
1312 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001313 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001314}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001315
Alex Lighta59dd802014-07-02 16:28:08 -07001316const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1317 InstructionSet isa,
1318 bool *already_opened,
1319 bool *obsolete_file_cleanup_failed,
1320 std::vector<std::string>* error_msgs) {
1321 // Find out if we've already opened the file
1322 const OatFile* ret = nullptr;
1323 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1324 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1325 if (ret != nullptr) {
1326 *already_opened = true;
1327 return ret;
1328 }
1329
1330 std::string dalvik_cache;
1331 bool have_android_data = false;
1332 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001333 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001334 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001335 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001336 std::string cache_filename;
1337 if (have_dalvik_cache) {
1338 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1339 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1340 if (ret != nullptr) {
1341 *already_opened = true;
1342 return ret;
1343 }
1344 } else {
1345 // If we need to relocate we should just place odex back where it started.
1346 cache_filename = odex_filename;
1347 }
1348
1349 ret = nullptr;
1350
1351 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1352 //
1353 // Now we do the following:
1354 // 1) Try and open the odex version
1355 // 2) If present, checksum-verified & relocated correctly return it
1356 // 3) Close the odex version to free up its address space.
1357 // 4) Try and open the cache version
1358 // 5) If present, checksum-verified & relocated correctly return it
1359 // 6) Close the cache version to free up its address space.
1360 // 7) If we should relocate:
1361 // a) If we have opened and checksum-verified the odex version relocate it to
1362 // 'cache_filename' and return it
1363 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1364 // it. This should not happen often (I think only the run-test's will hit this case).
1365 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1366 // this point.
1367 // 9) Return nullptr
1368
1369 *already_opened = false;
1370 const Runtime* runtime = Runtime::Current();
1371 CHECK(runtime != nullptr);
1372 bool executable = !runtime->IsCompiler();
1373
1374 std::string odex_error_msg;
1375 bool should_patch_system = false;
1376 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001377 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001378 {
1379 // There is a high probability that these both these oat files map similar/the same address
1380 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001381 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001382 executable, &odex_error_msg));
1383 if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1384 &odex_checksum_verified,
1385 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001386 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001387 } else {
1388 if (odex_checksum_verified) {
1389 // We can just relocate
1390 should_patch_system = true;
1391 odex_error_msg = "Image Patches are incorrect";
1392 }
1393 if (odex_oat_file.get() != nullptr) {
1394 have_system_odex = true;
1395 }
Alex Lighta59dd802014-07-02 16:28:08 -07001396 }
1397 }
1398
Alex Lighta59dd802014-07-02 16:28:08 -07001399 std::string cache_error_msg;
1400 bool should_patch_cache = false;
1401 bool cache_checksum_verified = false;
1402 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001403 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001404 executable, &cache_error_msg));
1405 if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1406 &cache_checksum_verified,
1407 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001408 return cache_oat_file.release();
1409 } else if (cache_checksum_verified) {
1410 // We can just relocate
1411 should_patch_cache = true;
1412 cache_error_msg = "Image Patches are incorrect";
1413 }
1414 } else if (have_android_data) {
1415 // dalvik_cache does not exist but android data does. This means we should be able to create
1416 // it, so we should try.
1417 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1418 }
1419
1420 ret = nullptr;
1421 std::string error_msg;
1422 if (runtime->CanRelocate()) {
1423 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001424 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1425 if (space != nullptr) {
1426 const std::string& image_location = space->GetImageLocation();
1427 if (odex_checksum_verified && should_patch_system) {
1428 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1429 } else if (cache_checksum_verified && should_patch_cache) {
1430 CHECK(have_dalvik_cache);
1431 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1432 }
Alex Light84d76052014-08-22 17:49:35 -07001433 } else if (have_system_odex) {
1434 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001435 }
1436 }
1437 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1438 // implicitly: were able to fine where the cached version is but we were unable to use it,
1439 // either as a destination for relocation or to open a file. We should delete it if it is
1440 // there.
1441 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1442 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1443 "searching for dex file %s: %s",
1444 cache_filename.c_str(), dex_location.c_str(),
1445 strerror(errno));
1446 error_msgs->push_back(rm_error_msg);
1447 VLOG(class_linker) << rm_error_msg;
1448 // Let the caller know that we couldn't remove the obsolete file.
1449 // This is a good indication that further writes may fail as well.
1450 *obsolete_file_cleanup_failed = true;
1451 }
1452 }
1453 if (ret == nullptr) {
1454 VLOG(class_linker) << error_msg;
1455 error_msgs->push_back(error_msg);
1456 std::string relocation_msg;
1457 if (runtime->CanRelocate()) {
1458 relocation_msg = StringPrintf(" and relocation failed");
1459 }
1460 if (have_dalvik_cache && cache_checksum_verified) {
1461 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1462 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1463 cache_filename.c_str(), cache_error_msg.c_str(),
1464 relocation_msg.c_str());
1465 } else {
1466 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1467 "dalvik_cache availible)%s.", odex_filename.c_str(),
1468 odex_error_msg.c_str(), relocation_msg.c_str());
1469 }
1470 VLOG(class_linker) << error_msg;
1471 error_msgs->push_back(error_msg);
1472 }
1473 return ret;
1474}
1475
Alex Light9dcc4572014-08-14 14:16:26 -07001476const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1477 InstructionSet isa,
1478 std::string* error_msg) {
1479 // We open it non-executable
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001480 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001481 if (output.get() == nullptr) {
1482 return nullptr;
1483 }
Alex Light84d76052014-08-22 17:49:35 -07001484 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1485 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001486 return output.release();
1487 } else {
1488 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1489 oat_path.c_str());
1490 return nullptr;
1491 }
1492}
1493
Alex Lighta59dd802014-07-02 16:28:08 -07001494const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1495 const std::string& output_oat,
1496 const std::string& image_location,
1497 InstructionSet isa,
1498 std::string* error_msg) {
Alex Light64ad14d2014-08-19 14:23:13 -07001499 if (!Runtime::Current()->GetHeap()->HasImageSpace()) {
1500 // We don't have an image space so there is no point in trying to patchoat.
1501 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1502 << "running without an image. Attempting to use oat file for interpretation.";
1503 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1504 }
Alex Light9dcc4572014-08-14 14:16:26 -07001505 if (!Runtime::Current()->IsDex2OatEnabled()) {
1506 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1507 // input_oat but make sure we only do interpretation on it's dex files.
1508 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1509 << "disabled. Attempting to use oat file for interpretation";
1510 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1511 }
Alex Lighta59dd802014-07-02 16:28:08 -07001512 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
1513 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1514
1515 std::string isa_arg("--instruction-set=");
1516 isa_arg += GetInstructionSetString(isa);
1517 std::string input_oat_filename_arg("--input-oat-file=");
1518 input_oat_filename_arg += input_oat;
1519 std::string output_oat_filename_arg("--output-oat-file=");
1520 output_oat_filename_arg += output_oat;
1521 std::string patched_image_arg("--patched-image-location=");
1522 patched_image_arg += image_location;
1523
1524 std::vector<std::string> argv;
1525 argv.push_back(patchoat);
1526 argv.push_back(isa_arg);
1527 argv.push_back(input_oat_filename_arg);
1528 argv.push_back(output_oat_filename_arg);
1529 argv.push_back(patched_image_arg);
1530
1531 std::string command_line(Join(argv, ' '));
1532 LOG(INFO) << "Relocate Oat File: " << command_line;
1533 bool success = Exec(argv, error_msg);
1534 if (success) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001535 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001536 !Runtime::Current()->IsCompiler(), error_msg));
1537 bool checksum_verified = false;
1538 if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1539 return output.release();
1540 } else if (output.get() != nullptr) {
1541 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1542 "but output file '%s' failed verifcation: %s",
1543 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1544 } else {
1545 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1546 "but was unable to open output file '%s': %s",
1547 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1548 }
Alex Light9dcc4572014-08-14 14:16:26 -07001549 } else if (!Runtime::Current()->IsCompiler()) {
1550 // patchoat failed which means we probably don't have enough room to place the output oat file,
1551 // instead of failing we should just run the interpreter from the dex files in the input oat.
1552 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1553 << "for interpretation. patchoat failure was: " << *error_msg;
1554 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001555 } else {
1556 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1557 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1558 error_msg->c_str());
1559 }
1560 return nullptr;
1561}
1562
1563int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1564 Runtime* runtime = Runtime::Current();
1565 int32_t real_patch_delta;
1566 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001567 CHECK(image_space != nullptr);
Alex Lighta59dd802014-07-02 16:28:08 -07001568 if (isa == Runtime::Current()->GetInstructionSet()) {
1569 const ImageHeader& image_header = image_space->GetImageHeader();
1570 real_patch_delta = image_header.GetPatchDelta();
1571 } else {
1572 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1573 image_space->GetImageLocation().c_str(), isa));
1574 real_patch_delta = image_header->GetPatchDelta();
1575 }
1576 const OatHeader& oat_header = oat_file->GetOatHeader();
1577 return real_patch_delta - oat_header.GetImagePatchDelta();
1578}
1579
1580bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1581 bool* checksum_verified,
1582 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001583 Runtime* runtime = Runtime::Current();
Alex Lighta59dd802014-07-02 16:28:08 -07001584 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001585 if (image_space == nullptr) {
1586 *error_msg = "No image space present";
1587 return false;
1588 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001589 uint32_t real_image_checksum;
1590 void* real_image_oat_offset;
1591 int32_t real_patch_delta;
1592 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001593 const ImageHeader& image_header = image_space->GetImageHeader();
1594 real_image_checksum = image_header.GetOatChecksum();
1595 real_image_oat_offset = image_header.GetOatDataBegin();
1596 real_patch_delta = image_header.GetPatchDelta();
1597 } else {
1598 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1599 image_space->GetImageLocation().c_str(), isa));
1600 real_image_checksum = image_header->GetOatChecksum();
1601 real_image_oat_offset = image_header->GetOatDataBegin();
1602 real_patch_delta = image_header->GetPatchDelta();
1603 }
1604
1605 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001606 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001607
1608 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1609 *checksum_verified = oat_image_checksum == real_image_checksum;
1610 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001611 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1612 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001613 }
1614
1615 void* oat_image_oat_offset =
1616 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1617 bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1618 if (!offset_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001619 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1620 real_image_oat_offset, oat_image_oat_offset);
Alex Lighta59dd802014-07-02 16:28:08 -07001621 }
1622
1623 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1624 bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1625 if (!patch_delta_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001626 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, received 0x%x)",
1627 real_patch_delta, oat_patch_delta);
Alex Lighta59dd802014-07-02 16:28:08 -07001628 }
1629
1630 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001631 if (!ret) {
1632 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001633 }
1634 return ret;
1635}
1636
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001637const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1638 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001639 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001640 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001641 return oat_file;
1642 }
1643
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001644 return OatFile::Open(oat_location, oat_location, nullptr, !Runtime::Current()->IsCompiler(),
1645 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001646}
1647
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001648static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001649 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001650 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1651
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001652 DCHECK(obj != nullptr);
1653 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001654
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001655 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001656 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001657 if (!method->IsNative()) {
1658 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1659 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001660 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1661 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001662 }
1663 }
1664 }
1665}
1666
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001667void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001668 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001669 CHECK(!init_done_);
1670
Mathieu Chartier590fee92013-09-13 13:46:47 -07001671 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001672 gc::Heap* heap = Runtime::Current()->GetHeap();
1673 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001674 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001675 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001676 OatFile& oat_file = GetImageOatFile(space);
1677 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1678 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001679 const char* image_file_location = oat_file.GetOatHeader().
1680 GetStoreValueByKey(OatHeader::kImageLocationKey);
1681 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001682 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1683 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001684 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1685 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001686 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001687 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001688 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1689 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1690 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001691
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001692 StackHandleScope<1> hs(self);
1693 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1694 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1695 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001696 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001697
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001698 // Special case of setting up the String class early so that we can test arbitrary objects
1699 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001700 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001701
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001702 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001703 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001704 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001705 StackHandleScope<1> hs(self);
1706 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001707 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001708 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1709 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001710 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001711 std::string error_msg;
1712 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001713 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001714 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001715 << " from within oat file " << oat_file.GetLocation()
1716 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001717 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001718
1719 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1720
1721 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001722 }
1723
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001724 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1725 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001726 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001727
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001728 // Set entry point to interpreter if in InterpretOnly mode.
1729 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001730 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001731 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001732 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001733
1734 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001735 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001736 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001737
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001738 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001739 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1740 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001741 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001742 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001743 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001744 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1745 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1746 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1747 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1748 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1749 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1750 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1751 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1752 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1753 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001754
Ian Rogers98379392014-02-24 16:53:16 -08001755 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001756
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001757 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001758}
1759
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001760void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1761 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1762 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001763 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1764 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001765 }
1766 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1767 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001768 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1769 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1770 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1771 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001772 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1773 // corresponding object. This is slow, but luckily for us, this may only happen with a
1774 // concurrent moving GC.
1775 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1776 it != end && it->first == pair.first; ++it) {
1777 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001778 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1779 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001780 }
1781 }
1782 }
1783 }
1784 }
1785 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1786 new_class_roots_.clear();
1787 }
1788 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1789 log_new_class_table_roots_ = true;
1790 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1791 log_new_class_table_roots_ = false;
1792 }
1793 // We deliberately ignore the class roots in the image since we
1794 // handle image roots by using the MS/CMS rescanning of dirty cards.
1795}
1796
Brian Carlstroma663ea52011-08-19 23:33:41 -07001797// Keep in sync with InitCallback. Anything we visit, we need to
1798// reinit references to when reinitializing a ClassLinker from a
1799// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001800void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001801 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001802 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001803 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001804 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001805 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001806 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1807 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001808 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001809 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1810 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001811 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001812 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001813 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001814 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1815 new_dex_cache_roots_.clear();
1816 }
1817 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1818 log_new_dex_caches_roots_ = true;
1819 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1820 log_new_dex_caches_roots_ = false;
1821 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001822 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001823 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001824 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1825 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001826 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001827 if (!find_array_class_cache_[i].IsNull()) {
1828 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001829 }
1830 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001831}
1832
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001833void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1834 if (dex_cache_image_class_lookup_required_) {
1835 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001836 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001837 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001838 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001839 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1840 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001841 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001842 return;
1843 }
1844 }
1845}
1846
Ian Rogersdbf3be02014-08-29 15:40:08 -07001847static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001848 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001849 classes->insert(c);
1850 return true;
1851}
1852
Ian Rogersdbf3be02014-08-29 15:40:08 -07001853struct GetClassesVisitorArrayArg {
1854 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1855 int32_t index;
1856 bool success;
1857};
1858
1859static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1860 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1861 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1862 if (arg->index < (*arg->classes)->GetLength()) {
1863 (*arg->classes)->Set(arg->index, c);
1864 arg->index++;
1865 return true;
1866 } else {
1867 arg->success = false;
1868 return false;
1869 }
1870}
1871
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001872void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001873 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1874 // is avoiding duplicates.
1875 if (!kMovingClasses) {
1876 std::set<mirror::Class*> classes;
1877 VisitClasses(GetClassesVisitorSet, &classes);
1878 for (mirror::Class* klass : classes) {
1879 if (!visitor(klass, arg)) {
1880 return;
1881 }
1882 }
1883 } else {
1884 Thread* self = Thread::Current();
1885 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001886 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001887 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1888 GetClassesVisitorArrayArg local_arg;
1889 local_arg.classes = &classes;
1890 local_arg.success = false;
1891 // We size the array assuming classes won't be added to the class table during the visit.
1892 // If this assumption fails we iterate again.
1893 while (!local_arg.success) {
1894 size_t class_table_size;
1895 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001896 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001897 class_table_size = class_table_.size();
1898 }
1899 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1900 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1901 classes.Assign(
1902 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1903 CHECK(classes.Get() != nullptr); // OOME.
1904 local_arg.index = 0;
1905 local_arg.success = true;
1906 VisitClasses(GetClassesVisitorArray, &local_arg);
1907 }
1908 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1909 // If the class table shrank during creation of the clases array we expect null elements. If
1910 // the class table grew then the loop repeats. If classes are created after the loop has
1911 // finished then we don't visit.
1912 mirror::Class* klass = classes->Get(i);
1913 if (klass != nullptr && !visitor(klass, arg)) {
1914 return;
1915 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001916 }
1917 }
1918}
1919
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001920ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001921 mirror::Class::ResetClass();
1922 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001923 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001924 mirror::ArtField::ResetClass();
1925 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001926 mirror::BooleanArray::ResetArrayClass();
1927 mirror::ByteArray::ResetArrayClass();
1928 mirror::CharArray::ResetArrayClass();
1929 mirror::DoubleArray::ResetArrayClass();
1930 mirror::FloatArray::ResetArrayClass();
1931 mirror::IntArray::ResetArrayClass();
1932 mirror::LongArray::ResetArrayClass();
1933 mirror::ShortArray::ResetArrayClass();
1934 mirror::Throwable::ResetClass();
1935 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001936 STLDeleteElements(&boot_class_path_);
1937 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001938}
1939
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001940mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001941 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001942 StackHandleScope<16> hs(self);
1943 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1944 Handle<mirror::DexCache> dex_cache(
1945 hs.NewHandle(down_cast<mirror::DexCache*>(
1946 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1947 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001948 if (dex_cache.Get() == nullptr) {
1949 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001950 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001951 Handle<mirror::String>
1952 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001953 if (location.Get() == nullptr) {
1954 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001955 }
Ian Rogers700a4022014-05-19 16:49:03 -07001956 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001957 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001958 if (strings.Get() == nullptr) {
1959 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001960 }
Ian Rogers700a4022014-05-19 16:49:03 -07001961 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001962 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001963 if (types.Get() == nullptr) {
1964 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001965 }
Ian Rogers700a4022014-05-19 16:49:03 -07001966 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001967 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001968 if (methods.Get() == nullptr) {
1969 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001970 }
Ian Rogers700a4022014-05-19 16:49:03 -07001971 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001972 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001973 if (fields.Get() == nullptr) {
1974 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001975 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001976 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1977 fields.Get());
1978 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001979}
1980
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001981mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001982 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001983 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001984 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001985 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001986 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001987 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1988 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001989 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001990 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001991 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001992 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001993 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001994}
1995
Ian Rogers6fac4472014-02-25 17:01:10 -08001996mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001997 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001998}
1999
Brian Carlstromea46f952013-07-30 01:26:50 -07002000mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002001 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002002 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07002003}
2004
Brian Carlstromea46f952013-07-30 01:26:50 -07002005mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002006 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002007 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002008}
2009
Mathieu Chartier590fee92013-09-13 13:46:47 -07002010mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2011 Thread* self, size_t length) {
2012 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2013 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002014}
2015
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002016mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2017 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002018 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002019
2020 // For temporary classes we must wait for them to be retired.
2021 if (init_done_ && klass->IsTemp()) {
2022 CHECK(!klass->IsResolved());
2023 if (klass->IsErroneous()) {
2024 ThrowEarlierClassFailure(klass);
2025 return nullptr;
2026 }
2027 StackHandleScope<1> hs(self);
2028 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2029 ObjectLock<mirror::Class> lock(self, h_class);
2030 // Loop and wait for the resolving thread to retire this class.
2031 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2032 lock.WaitIgnoringInterrupts();
2033 }
2034 if (h_class->IsErroneous()) {
2035 ThrowEarlierClassFailure(h_class.Get());
2036 return nullptr;
2037 }
2038 CHECK(h_class->IsRetired());
2039 // Get the updated class from class table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002040 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002041 }
2042
Brian Carlstromaded5f72011-10-07 17:15:04 -07002043 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002044 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002045 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002046 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2047 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002048 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002049 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2050 ThrowClassCircularityError(h_class.Get());
2051 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002052 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002053 }
2054 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002055 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002056 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002057 }
2058 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002059
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002060 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002061 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002062 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002063 }
2064 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002065 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002066 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002067 return klass;
2068}
2069
Ian Rogers68b56852014-08-29 20:19:11 -07002070typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2071
2072// Search a collection of DexFiles for a descriptor
2073ClassPathEntry FindInClassPath(const char* descriptor,
2074 const std::vector<const DexFile*>& class_path) {
2075 for (size_t i = 0; i != class_path.size(); ++i) {
2076 const DexFile* dex_file = class_path[i];
2077 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002078 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002079 return ClassPathEntry(dex_file, dex_class_def);
2080 }
2081 }
2082 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002083 return ClassPathEntry(static_cast<const DexFile*>(nullptr),
2084 static_cast<const DexFile::ClassDef*>(nullptr));
Ian Rogers68b56852014-08-29 20:19:11 -07002085}
2086
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002087mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2088 Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002089 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002090 if (class_loader->GetClass() !=
2091 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2092 class_loader->GetParent()->GetClass() !=
2093 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2094 return nullptr;
2095 }
2096 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2097 // Check if this would be found in the parent boot class loader.
2098 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002099 mirror::Class* klass = LookupClass(self, descriptor, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002100 if (klass != nullptr) {
2101 return EnsureResolved(self, descriptor, klass);
2102 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002103 klass = DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002104 *pair.second);
2105 if (klass != nullptr) {
2106 return klass;
2107 }
2108 CHECK(self->IsExceptionPending()) << descriptor;
2109 self->ClearException();
2110 } else {
2111 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2112 StackHandleScope<3> hs(self);
2113 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2114 // We need to get the DexPathList and loop through it.
2115 Handle<mirror::ArtField> cookie_field =
2116 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2117 Handle<mirror::ArtField> dex_file_field =
2118 hs.NewHandle(
2119 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList$Element_dexFile));
2120 mirror::Object* dex_path_list =
2121 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2122 GetObject(class_loader.Get());
2123 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2124 cookie_field.Get() != nullptr) {
2125 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2126 mirror::Object* dex_elements_obj =
2127 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2128 GetObject(dex_path_list);
2129 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2130 // at the mCookie which is a DexFile vector.
2131 if (dex_elements_obj != nullptr) {
2132 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2133 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2134 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2135 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2136 if (element == nullptr) {
2137 // Should never happen, fall back to java code to throw a NPE.
2138 break;
2139 }
2140 mirror::Object* dex_file = dex_file_field->GetObject(element);
2141 if (dex_file != nullptr) {
2142 const uint64_t cookie = cookie_field->GetLong(dex_file);
2143 auto* dex_files =
2144 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2145 if (dex_files == nullptr) {
2146 // This should never happen so log a warning.
2147 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2148 break;
2149 }
2150 for (const DexFile* dex_file : *dex_files) {
2151 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
2152 if (dex_class_def != nullptr) {
2153 RegisterDexFile(*dex_file);
2154 mirror::Class* klass =
Ian Rogers7b078e82014-09-10 14:44:24 -07002155 DefineClass(self, descriptor, class_loader, *dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002156 if (klass == nullptr) {
2157 CHECK(self->IsExceptionPending()) << descriptor;
2158 self->ClearException();
2159 return nullptr;
2160 }
2161 return klass;
2162 }
2163 }
2164 }
2165 }
2166 }
2167 }
2168 }
2169 return nullptr;
2170}
2171
Ian Rogers98379392014-02-24 16:53:16 -08002172mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002173 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002174 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002175 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002176 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002177 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002178 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2179 // for primitive classes that aren't backed by dex files.
2180 return FindPrimitiveClass(descriptor[0]);
2181 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002182 // Find the class in the loaded classes table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002183 mirror::Class* klass = LookupClass(self, descriptor, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002184 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002185 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002186 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002187 // Class is not yet loaded.
2188 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08002189 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002190 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002191 // The boot class loader, search the boot class path.
Ian Rogers68b56852014-08-29 20:19:11 -07002192 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2193 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002194 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2195 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002196 } else {
2197 // The boot class loader is searched ahead of the application class loader, failures are
2198 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2199 // trigger the chaining with a proper stack trace.
2200 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2201 self->SetException(ThrowLocation(), pre_allocated);
2202 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002203 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002204 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002205 // First try with the bootstrap class loader.
2206 if (class_loader.Get() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002207 klass = LookupClass(self, descriptor, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002208 if (klass != nullptr) {
2209 return EnsureResolved(self, descriptor, klass);
2210 }
2211 }
Ian Rogers63557452014-06-04 16:57:15 -07002212 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2213 // a NoClassDefFoundError being allocated.
Ian Rogers68b56852014-08-29 20:19:11 -07002214 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2215 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002216 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2217 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002218 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002219 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002220 const std::vector<const DexFile*>* class_path;
2221 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002222 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002223 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002224 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002225 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2226 }
Ian Rogers68b56852014-08-29 20:19:11 -07002227 pair = FindInClassPath(descriptor, *class_path);
2228 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002229 return DefineClass(self, descriptor, class_loader, *pair.first, *pair.second);
2230 } else {
2231 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2232 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2233 self->SetException(ThrowLocation(), pre_allocated);
2234 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002235 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002236 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002237 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002238 mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, class_loader);
2239 if (klass != nullptr) {
2240 return klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002241 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002242 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002243 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002244 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002245 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002246 {
2247 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002248 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2249 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002250 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002251 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002252 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002253 }
Ian Rogers68b56852014-08-29 20:19:11 -07002254 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002255 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2256 WellKnownClasses::java_lang_ClassLoader_loadClass,
2257 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002258 }
Ian Rogers98379392014-02-24 16:53:16 -08002259 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002260 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002261 return nullptr;
2262 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002263 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002264 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002265 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002266 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002267 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002268 // success, return mirror::Class*
2269 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002270 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002271 }
2272
Elliott Hughes82914b62012-04-09 15:56:29 -07002273 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002274 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002275}
2276
Ian Rogers7b078e82014-09-10 14:44:24 -07002277mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002278 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002279 const DexFile& dex_file,
2280 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002281 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002282 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002283 bool should_allocate = false;
2284
Brian Carlstromaded5f72011-10-07 17:15:04 -07002285 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002286 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002287 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002288 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002289 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002290 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002291 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002292 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002293 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002294 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2295 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002296 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002297 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002298 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002299 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002300 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002301 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002302 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002303 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002304 }
2305 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002306 should_allocate = true;
2307 }
2308
2309 if (should_allocate) {
2310 // Allocate a class with the status of not ready.
2311 // Interface object should get the right size here. Regular class will
2312 // figure out the right size later and be replaced with one of the right
2313 // size when the class becomes resolved.
2314 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002315 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002316 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002317 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002318 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002319 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002320 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002321 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002322 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002323 if (self->IsExceptionPending()) {
2324 // An exception occured during load, set status to erroneous while holding klass' lock in case
2325 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002326 if (!klass->IsErroneous()) {
2327 klass->SetStatus(mirror::Class::kStatusError, self);
2328 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002329 return nullptr;
2330 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002331 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002332
Mathieu Chartier590fee92013-09-13 13:46:47 -07002333 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002334 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07002335 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002336 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2337 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002338 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002339 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002340
Brian Carlstromaded5f72011-10-07 17:15:04 -07002341 // Finish loading (if necessary) by finding parents
2342 CHECK(!klass->IsLoaded());
2343 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2344 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002345 if (!klass->IsErroneous()) {
2346 klass->SetStatus(mirror::Class::kStatusError, self);
2347 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002348 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002349 }
2350 CHECK(klass->IsLoaded());
2351 // Link the class (if necessary)
2352 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002353 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002354 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002355
2356 mirror::Class* new_class = nullptr;
2357 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002358 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002359 if (!klass->IsErroneous()) {
2360 klass->SetStatus(mirror::Class::kStatusError, self);
2361 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002362 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002363 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002364 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002365 CHECK(new_class != nullptr) << descriptor;
2366 CHECK(new_class->IsResolved()) << descriptor;
2367
2368 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002369
2370 /*
2371 * We send CLASS_PREPARE events to the debugger from here. The
2372 * definition of "preparation" is creating the static fields for a
2373 * class and initializing them to the standard default values, but not
2374 * executing any code (that comes later, during "initialization").
2375 *
2376 * We did the static preparation in LinkClass.
2377 *
2378 * The class has been prepared and resolved but possibly not yet verified
2379 * at this point.
2380 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002381 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002382
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002383 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002384}
2385
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002386uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2387 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002388 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002389 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002390 size_t num_8 = 0;
2391 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002392 size_t num_32 = 0;
2393 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002394 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002395 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2396 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002397 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002398 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002399 switch (c) {
2400 case 'L':
2401 case '[':
2402 num_ref++;
2403 break;
2404 case 'J':
2405 case 'D':
2406 num_64++;
2407 break;
2408 case 'I':
2409 case 'F':
2410 num_32++;
2411 break;
2412 case 'S':
2413 case 'C':
2414 num_16++;
2415 break;
2416 case 'B':
2417 case 'Z':
2418 num_8++;
2419 break;
2420 default:
2421 LOG(FATAL) << "Unknown descriptor: " << c;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002422 }
2423 }
2424 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002425 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002426}
2427
Ian Rogers97b52f82014-08-14 11:34:07 -07002428OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2429 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002430 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002431 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2432 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002433 *found = false;
2434 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002435 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002436 *found = true;
2437 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002438}
2439
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002440static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2441 uint32_t method_idx) {
2442 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2443 const byte* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002444 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002445 ClassDataItemIterator it(dex_file, class_data);
2446 // Skip fields
2447 while (it.HasNextStaticField()) {
2448 it.Next();
2449 }
2450 while (it.HasNextInstanceField()) {
2451 it.Next();
2452 }
2453 // Process methods
2454 size_t class_def_method_index = 0;
2455 while (it.HasNextDirectMethod()) {
2456 if (it.GetMemberIndex() == method_idx) {
2457 return class_def_method_index;
2458 }
2459 class_def_method_index++;
2460 it.Next();
2461 }
2462 while (it.HasNextVirtualMethod()) {
2463 if (it.GetMemberIndex() == method_idx) {
2464 return class_def_method_index;
2465 }
2466 class_def_method_index++;
2467 it.Next();
2468 }
2469 DCHECK(!it.HasNext());
2470 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2471 return 0;
2472}
2473
Ian Rogers97b52f82014-08-14 11:34:07 -07002474const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002475 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002476 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002477 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002478 size_t oat_method_index;
2479 if (method->IsStatic() || method->IsDirect()) {
2480 // Simple case where the oat method index was stashed at load time.
2481 oat_method_index = method->GetMethodIndex();
2482 } else {
2483 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2484 // by search for its position in the declared virtual methods.
2485 oat_method_index = declaring_class->NumDirectMethods();
2486 size_t end = declaring_class->NumVirtualMethods();
2487 bool found = false;
2488 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002489 // Check method index instead of identity in case of duplicate method definitions.
2490 if (method->GetDexMethodIndex() ==
2491 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002492 found = true;
2493 break;
2494 }
Ian Rogersf320b632012-03-13 18:47:47 -07002495 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002496 }
2497 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2498 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002499 DCHECK_EQ(oat_method_index,
2500 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002501 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002502 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002503 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2504 declaring_class->GetDexClassDefIndex(),
2505 found);
2506 if (!found) {
2507 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002508 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002509 *found = true;
2510 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002511}
2512
2513// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002514const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002515 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002516 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002517 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002518 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002519 bool found;
2520 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002521 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002522 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002523 result = oat_method.GetQuickCode();
2524 }
2525
Ian Rogersef7d42f2014-01-06 12:55:46 -08002526 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002527 if (method->IsNative()) {
2528 // No code and native? Use generic trampoline.
2529 result = GetQuickGenericJniTrampoline();
2530 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002531 // No code? Do we expect portable code?
2532 result = GetQuickToPortableBridge();
2533 } else {
2534 // No code? You must mean to go into the interpreter.
2535 result = GetQuickToInterpreterBridge();
2536 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002537 }
2538 return result;
TDYa12785321912012-04-01 15:24:56 -07002539}
2540
Ian Rogersef7d42f2014-01-06 12:55:46 -08002541const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2542 bool* have_portable_code) {
2543 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2544 *have_portable_code = false;
2545 if (method->IsProxyMethod()) {
2546 return GetPortableProxyInvokeHandler();
2547 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002548 bool found;
2549 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002550 const void* result = nullptr;
2551 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002552 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002553 result = oat_method.GetPortableCode();
2554 quick_code = oat_method.GetQuickCode();
2555 }
2556
Ian Rogersef7d42f2014-01-06 12:55:46 -08002557 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002558 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002559 // No code? You must mean to go into the interpreter.
2560 result = GetPortableToInterpreterBridge();
2561 } else {
2562 // No code? But there's quick code, so use a bridge.
2563 result = GetPortableToQuickBridge();
2564 }
2565 } else {
2566 *have_portable_code = true;
2567 }
2568 return result;
2569}
2570
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002571const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2572 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2573 return nullptr;
2574 }
2575 bool found;
2576 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2577 return found ? oat_method.GetQuickCode() : nullptr;
2578}
2579
2580const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2581 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2582 return nullptr;
2583 }
2584 bool found;
2585 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2586 return found ? oat_method.GetPortableCode() : nullptr;
2587}
2588
Ian Rogersef7d42f2014-01-06 12:55:46 -08002589const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2590 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002591 bool found;
2592 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2593 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002594 return nullptr;
2595 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002596 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002597 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002598}
2599
2600const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2601 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002602 bool found;
2603 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2604 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002605 return nullptr;
2606 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002607 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002608 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002609}
2610
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002611// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002612static bool NeedsInterpreter(
2613 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2614 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002615 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002616 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002617 // May return true for native code, in the case of generic JNI
2618 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002619 return true;
2620 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002621#ifdef ART_SEA_IR_MODE
2622 ScopedObjectAccess soa(Thread::Current());
2623 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2624 LOG(INFO) << "Found " << PrettyMethod(method);
2625 return false;
2626 }
2627#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002628 // If interpreter mode is enabled, every method (except native and proxy) must
2629 // be run with interpreter.
2630 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2631 !method->IsNative() && !method->IsProxyMethod();
2632}
2633
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002634void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002635 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002636 if (klass->NumDirectMethods() == 0) {
2637 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002638 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002639 Runtime* runtime = Runtime::Current();
2640 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002641 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2642 return; // OAT file unavailable.
2643 }
Ian Rogers19846512012-02-24 11:42:47 -08002644 }
Alex Light64ad14d2014-08-19 14:23:13 -07002645
Mathieu Chartierf8322842014-05-16 10:59:25 -07002646 const DexFile& dex_file = klass->GetDexFile();
2647 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002648 CHECK(dex_class_def != nullptr);
2649 const byte* class_data = dex_file.GetClassData(*dex_class_def);
2650 // There should always be class data if there were direct methods.
2651 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002652 ClassDataItemIterator it(dex_file, class_data);
2653 // Skip fields
2654 while (it.HasNextStaticField()) {
2655 it.Next();
2656 }
2657 while (it.HasNextInstanceField()) {
2658 it.Next();
2659 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002660 bool has_oat_class;
2661 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2662 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002663 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002664 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002665 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002666 if (!method->IsStatic()) {
2667 // Only update static methods.
2668 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002669 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002670 const void* portable_code = nullptr;
2671 const void* quick_code = nullptr;
2672 if (has_oat_class) {
2673 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2674 portable_code = oat_method.GetPortableCode();
2675 quick_code = oat_method.GetQuickCode();
2676 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002677 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2678 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002679 if (enter_interpreter) {
2680 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002681 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002682 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2683 quick_code = GetQuickGenericJniTrampoline();
Ian Rogers1a570662014-03-12 01:02:21 -07002684 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002685 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002686 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002687 quick_code = GetQuickToInterpreterBridge();
2688 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002689 } else {
2690 if (portable_code == nullptr) {
2691 portable_code = GetPortableToQuickBridge();
2692 } else {
2693 have_portable_code = true;
2694 }
2695 if (quick_code == nullptr) {
2696 quick_code = GetQuickToPortableBridge();
2697 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002698 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002699 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2700 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002701 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002702 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002703}
2704
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002705void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002706 const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002707 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002708 uint32_t method_index) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002709 if (Runtime::Current()->IsCompiler()) {
2710 // The following code only applies to a non-compiler runtime.
2711 return;
2712 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002713 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002714 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2715 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002716 if (oat_class != nullptr) {
2717 // Every kind of method should at least get an invoke stub from the oat_method.
2718 // non-abstract methods also get their code pointers.
2719 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2720 oat_method.LinkMethod(method.Get());
2721 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002722
Jeff Hao16743632013-05-08 10:59:04 -07002723 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002724 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002725 method->GetEntryPointFromQuickCompiledCode(),
2726 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002727 if (enter_interpreter && !method->IsNative()) {
Ian Rogers848871b2013-08-05 10:56:33 -07002728 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002729 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002730 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002731 }
2732
Brian Carlstrom92827a52011-10-10 15:50:01 -07002733 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002734 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2735 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002736 return;
2737 }
Ian Rogers19846512012-02-24 11:42:47 -08002738
Ian Rogersef7d42f2014-01-06 12:55:46 -08002739 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002740 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002741 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002742 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2743 // after initializing class (see ClassLinker::InitializeClass method).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002744 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline());
2745 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002746 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002747 if (!method->IsNative()) {
2748 // Set entry point from compiled code if there's no code or in interpreter only mode.
2749 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2750 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2751 } else {
2752 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline());
2753 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2754 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002755 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2756 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2757 have_portable_code = true;
2758 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2759 } else {
2760 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2761 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002762 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002763
Ian Rogers62d6c772013-02-27 08:32:07 -08002764 if (method->IsNative()) {
2765 // Unregistering restores the dlsym lookup stub.
2766 method->UnregisterNative(Thread::Current());
Andreas Gampe90546832014-03-12 18:07:19 -07002767
2768 if (enter_interpreter) {
2769 // We have a native method here without code. Then it should have either the GenericJni
2770 // trampoline as entrypoint (non-static), or the Resolution trampoline (static).
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002771 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline()
Andreas Gampe9a6a99a2014-03-14 07:52:20 -07002772 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline());
Andreas Gampe90546832014-03-12 18:07:19 -07002773 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002774 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002775
Ian Rogers62d6c772013-02-27 08:32:07 -08002776 // Allow instrumentation its chance to hijack code.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002777 Runtime* runtime = Runtime::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002778 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002779 method->GetEntryPointFromQuickCompiledCode(),
2780 method->GetEntryPointFromPortableCompiledCode(),
2781 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002782}
2783
Fred Shih37f05ef2014-07-16 18:38:08 -07002784
Fred Shih37f05ef2014-07-16 18:38:08 -07002785
Ian Rogers7b078e82014-09-10 14:44:24 -07002786void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002787 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002788 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002789 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002790 CHECK(klass.Get() != nullptr);
2791 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002792 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002793 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002794 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002795
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002796 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002797 if (kUseBakerOrBrooksReadBarrier) {
2798 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002799 }
Andreas Gampe51829322014-08-25 15:05:04 -07002800 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002801 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002802 klass->SetAccessFlags(access_flags);
2803 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002804 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002805 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002806
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002807 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002808 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002809
Ian Rogers0571d352011-11-03 19:51:38 -07002810 const byte* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002811 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002812 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002813 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002814
Ian Rogers97b52f82014-08-14 11:34:07 -07002815
2816 bool has_oat_class = false;
2817 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2818 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2819 &has_oat_class);
2820 if (has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002821 LoadClassMembers(self, dex_file, class_data, klass, class_loader, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002822 }
2823 }
2824 if (!has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002825 LoadClassMembers(self, dex_file, class_data, klass, class_loader, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002826 }
2827}
2828
Ian Rogers7b078e82014-09-10 14:44:24 -07002829void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002830 const byte* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002831 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002832 mirror::ClassLoader* class_loader,
2833 const OatFile::OatClass* oat_class) {
2834 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002835 ClassDataItemIterator it(dex_file, class_data);
2836 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002837 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002838 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002839 CHECK(self->IsExceptionPending()); // OOME.
2840 return;
2841 }
2842 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002843 }
2844 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002845 mirror::ObjectArray<mirror::ArtField>* fields =
2846 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002847 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002848 CHECK(self->IsExceptionPending()); // OOME.
2849 return;
2850 }
2851 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002852 }
2853 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002854 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002855 StackHandleScope<1> hs(self);
2856 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002857 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002858 CHECK(self->IsExceptionPending()); // OOME.
2859 return;
2860 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002861 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002862 LoadField(dex_file, it, klass, sfield);
2863 }
2864 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002865 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002866 StackHandleScope<1> hs(self);
2867 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002868 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002869 CHECK(self->IsExceptionPending()); // OOME.
2870 return;
2871 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002872 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002873 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002874 }
2875
Ian Rogers0571d352011-11-03 19:51:38 -07002876 // Load methods.
2877 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002878 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002879 mirror::ObjectArray<mirror::ArtMethod>* directs =
2880 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002881 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002882 CHECK(self->IsExceptionPending()); // OOME.
2883 return;
2884 }
2885 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002886 }
Ian Rogers0571d352011-11-03 19:51:38 -07002887 if (it.NumVirtualMethods() != 0) {
2888 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002889 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2890 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002891 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002892 CHECK(self->IsExceptionPending()); // OOME.
2893 return;
2894 }
2895 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002896 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002897 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002898 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2899 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002900 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002901 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002902 StackHandleScope<1> hs(self);
2903 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002904 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002905 CHECK(self->IsExceptionPending()); // OOME.
2906 return;
2907 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002908 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002909 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002910 uint32_t it_method_index = it.GetMemberIndex();
2911 if (last_dex_method_index == it_method_index) {
2912 // duplicate case
2913 method->SetMethodIndex(last_class_def_method_index);
2914 } else {
2915 method->SetMethodIndex(class_def_method_index);
2916 last_dex_method_index = it_method_index;
2917 last_class_def_method_index = class_def_method_index;
2918 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002919 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002920 }
2921 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002922 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002923 StackHandleScope<1> hs(self);
2924 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002925 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002926 CHECK(self->IsExceptionPending()); // OOME.
2927 return;
2928 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002929 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002930 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002931 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002932 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002933 }
2934 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002935}
2936
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002937void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002938 Handle<mirror::Class> klass,
2939 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002940 uint32_t field_idx = it.GetMemberIndex();
2941 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002942 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002943 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002944}
2945
Brian Carlstromea46f952013-07-30 01:26:50 -07002946mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002947 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002948 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002949 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002950 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002951 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002952
Brian Carlstromea46f952013-07-30 01:26:50 -07002953 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002954 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002955 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002956 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002957 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002958 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002959
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002960 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002961 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002962 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002963 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002964
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002965 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002966 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002967 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002968
Andreas Gampe51829322014-08-25 15:05:04 -07002969 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002970
Ian Rogersdfb325e2013-10-30 01:00:44 -07002971 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002972 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002973 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2974 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002975 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002976 klass->SetFinalizable();
2977 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002978 std::string temp;
2979 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002980 // The Enum class declares a "final" finalize() method to prevent subclasses from
2981 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2982 // subclasses, so we exclude it here.
2983 // We also want to avoid setting the flag on Object, where we know that finalize() is
2984 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002985 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2986 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002987 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002988 }
2989 }
2990 }
2991 } else if (method_name[0] == '<') {
2992 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002993 bool is_init = (strcmp("<init>", method_name) == 0);
2994 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002995 if (UNLIKELY(!is_init && !is_clinit)) {
2996 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2997 } else {
2998 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2999 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003000 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003001 access_flags |= kAccConstructor;
3002 }
3003 }
3004 }
3005 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003006
Mathieu Chartier66f19252012-09-18 08:57:04 -07003007 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07003008}
3009
Ian Rogers7b078e82014-09-10 14:44:24 -07003010void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003011 StackHandleScope<1> hs(self);
3012 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003013 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3014 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003015 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003016}
3017
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003018void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003019 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003020 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003021 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003022 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003023}
3024
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003025bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003026 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07003027 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003028 mirror::DexCache* dex_cache = GetDexCache(i);
3029 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08003030 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003031 }
3032 }
3033 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003034}
3035
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003036bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003037 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003038 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003039}
3040
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003041void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003042 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003043 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003044 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003045 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3046 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003047 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003048 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003049 if (log_new_dex_caches_roots_) {
3050 // TODO: This is not safe if we can remove dex caches.
3051 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3052 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003053}
3054
Brian Carlstromaded5f72011-10-07 17:15:04 -07003055void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003056 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003057 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003058 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003059 if (IsDexFileRegisteredLocked(dex_file)) {
3060 return;
3061 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003062 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003063 // Don't alloc while holding the lock, since allocation may need to
3064 // suspend all threads and another thread may need the dex_lock_ to
3065 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003066 StackHandleScope<1> hs(self);
3067 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003068 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3069 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003070 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003071 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003072 if (IsDexFileRegisteredLocked(dex_file)) {
3073 return;
3074 }
3075 RegisterDexFileLocked(dex_file, dex_cache);
3076 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003077}
3078
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003079void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003080 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003081 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003082 RegisterDexFileLocked(dex_file, dex_cache);
3083}
3084
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003085mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003086 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003087 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003088 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003089 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003090 if (dex_cache->GetDexFile() == &dex_file) {
3091 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003092 }
3093 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003094 // Search matching by location name.
3095 std::string location(dex_file.GetLocation());
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 if (dex_cache->GetDexFile()->GetLocation() == location) {
3099 return dex_cache;
3100 }
3101 }
3102 // Failure, dump diagnostic and abort.
3103 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003104 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003105 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3106 }
3107 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003108 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003109}
3110
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003111void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003112 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003113 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003114 mirror::DexCache* dex_cache = GetDexCache(i);
3115 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003116 }
3117}
3118
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003119mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003120 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003121 if (UNLIKELY(klass == nullptr)) {
3122 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003123 }
3124 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003125}
3126
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003127mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3128 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003129 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003130 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003131 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003132 StackHandleScope<1> hs(self);
3133 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003134 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003135 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003136 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003137 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3138 const char* descriptor = Primitive::Descriptor(type);
3139 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003140 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003141 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003142}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003143
Brian Carlstrombe977852011-07-19 14:54:54 -07003144// Create an array class (i.e. the class object for the array, not the
3145// array itself). "descriptor" looks like "[C" or "[[[[B" or
3146// "[Ljava/lang/String;".
3147//
3148// If "descriptor" refers to an array of primitives, look up the
3149// primitive type's internally-generated class object.
3150//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003151// "class_loader" is the class loader of the class that's referring to
3152// us. It's used to ensure that we're looking for the element type in
3153// the right context. It does NOT become the class loader for the
3154// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003155//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003156// Returns nullptr with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08003157mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003158 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003159 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003160 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003161 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003162 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3163 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003164 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003165 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003166 // We need to accept erroneous classes as component types.
Ian Rogers7b078e82014-09-10 14:44:24 -07003167 component_type.Assign(LookupClass(self, descriptor + 1, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003168 if (component_type.Get() == nullptr) {
3169 DCHECK(self->IsExceptionPending());
3170 return nullptr;
3171 } else {
3172 self->ClearException();
3173 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003174 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003175 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3176 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3177 return nullptr;
3178 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003179 // See if the component type is already loaded. Array classes are
3180 // always associated with the class loader of their underlying
3181 // element type -- an array of Strings goes with the loader for
3182 // java/lang/String -- so we need to look for it there. (The
3183 // caller should have checked for the existence of the class
3184 // before calling here, but they did so with *their* class loader,
3185 // not the component type's loader.)
3186 //
3187 // If we find it, the caller adds "loader" to the class' initiating
3188 // loader list, which should prevent us from going through this again.
3189 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003190 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003191 // are the same, because our caller (FindClass) just did the
3192 // lookup. (Even if we get this wrong we still have correct behavior,
3193 // because we effectively do this lookup again when we add the new
3194 // class to the hash table --- necessary because of possible races with
3195 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003196 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003197 mirror::Class* new_class = LookupClass(self, descriptor, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003198 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003199 return new_class;
3200 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003201 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003202
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003203 // Fill out the fields in the Class.
3204 //
3205 // It is possible to execute some methods against arrays, because
3206 // all arrays are subclasses of java_lang_Object_, so we need to set
3207 // up a vtable. We can just point at the one in java_lang_Object_.
3208 //
3209 // Array classes are simple enough that we don't need to do a full
3210 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003211 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003212 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003213 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003214 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003215 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003216 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003217 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003218 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003219 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003220 } else if (strcmp(descriptor,
3221 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003222 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003223 } else if (strcmp(descriptor,
3224 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003225 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003226 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003227 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003228 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003229 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003230 }
3231 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003232 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003233 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003234 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003235 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003236 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003237 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003238 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003239 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003240 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003241 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003242 new_class->SetSuperClass(java_lang_Object);
3243 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003244 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003245 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003246 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
3247 new_class->PopulateEmbeddedImtAndVTable();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003248 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003249 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003250 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003251
3252
3253 // All arrays have java/lang/Cloneable and java/io/Serializable as
3254 // interfaces. We need to set that up here, so that stuff like
3255 // "instanceof" works right.
3256 //
3257 // Note: The GC could run during the call to FindSystemClass,
3258 // so we need to make sure the class object is GC-valid while we're in
3259 // there. Do this by clearing the interface list so the GC will just
3260 // think that the entries are null.
3261
3262
3263 // Use the single, global copies of "interfaces" and "iftable"
3264 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003265 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003266 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003267 CHECK(array_iftable != nullptr);
3268 new_class->SetIfTable(array_iftable);
3269 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003270
Elliott Hughes00626c22013-06-14 15:04:14 -07003271 // Inherit access flags from the component type.
3272 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3273 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3274 access_flags &= kAccJavaFlagsMask;
3275 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003276 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003277 access_flags |= kAccAbstract | kAccFinal;
3278 access_flags &= ~kAccInterface;
3279
3280 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003281
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003282 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003283 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003284 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003285 }
3286 // Another thread must have loaded the class after we
3287 // started but before we finished. Abandon what we've
3288 // done.
3289 //
3290 // (Yes, this happens.)
3291
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003292 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003293}
3294
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003295mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003296 switch (type) {
3297 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003298 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003299 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003300 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003301 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003302 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003303 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003304 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003305 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003306 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003307 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003308 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003309 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003310 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003311 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003312 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003313 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003314 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003315 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003316 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003317 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003318 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003319 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003320 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003321}
3322
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003323mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3324 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003325 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003326 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003327 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003328 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003329 source += " from ";
3330 source += dex_cache->GetLocation()->ToModifiedUtf8();
3331 }
3332 LOG(INFO) << "Loaded class " << descriptor << source;
3333 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003334 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003335 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003336 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003337 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003338 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003339 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003340 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003341 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003342 // Check a class loaded with the system class loader matches one in the image if the class
3343 // is in the image.
3344 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003345 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003346 CHECK(klass == existing);
3347 }
3348 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003349 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003350 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003351 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003352 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003353 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003354 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003355}
3356
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003357mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3358 size_t hash) {
3359 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3360 mirror::Class* existing =
3361 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3362
3363 if (existing == nullptr) {
3364 CHECK(klass->IsProxyClass());
3365 return nullptr;
3366 }
3367
3368 CHECK_NE(existing, klass) << descriptor;
3369 CHECK(!existing->IsResolved()) << descriptor;
3370 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3371
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003372 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3373 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003374 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07003375 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003376 class_table_.erase(it);
3377 break;
3378 }
3379 }
3380
3381 CHECK(!klass->IsTemp()) << descriptor;
3382 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3383 dex_cache_image_class_lookup_required_) {
3384 // Check a class loaded with the system class loader matches one in the image if the class
3385 // is in the image.
3386 existing = LookupClassFromImage(descriptor);
3387 if (existing != nullptr) {
3388 CHECK(klass == existing) << descriptor;
3389 }
3390 }
3391 VerifyObject(klass);
3392
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003393 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003394 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003395 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003396 }
3397
3398 return existing;
3399}
3400
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003401bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003402 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003403 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07003404 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3405 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003406 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003407 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003408 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003409 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08003410 return true;
3411 }
3412 }
3413 return false;
3414}
3415
Ian Rogers7b078e82014-09-10 14:44:24 -07003416mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003417 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003418 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003419 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003420 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003421 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003422 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003423 return result;
3424 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003425 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003426 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3427 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003428 } else {
3429 // Lookup failed but need to search dex_caches_.
3430 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003431 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003432 InsertClass(descriptor, result, hash);
3433 } else {
3434 // Searching the image dex files/caches failed, we don't want to get into this situation
3435 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3436 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003437 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003438 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3439 MoveImageClassesToClassTable();
3440 }
3441 }
3442 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003443 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003444}
3445
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003446mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3447 const mirror::ClassLoader* class_loader,
3448 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003449 auto end = class_table_.end();
3450 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003451 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003452 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003453 if (kIsDebugBuild) {
3454 // Check for duplicates in the table.
3455 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003456 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003457 CHECK(!(klass2->GetClassLoader() == class_loader &&
3458 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003459 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3460 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003461 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003462 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003463 return klass;
3464 }
3465 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003466 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003467}
3468
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003469static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3470 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3471 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003472 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003473 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3474 return root->AsObjectArray<mirror::DexCache>();
3475}
3476
3477void ClassLinker::MoveImageClassesToClassTable() {
3478 Thread* self = Thread::Current();
3479 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3480 if (!dex_cache_image_class_lookup_required_) {
3481 return; // All dex cache classes are already in the class table.
3482 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003483 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003484 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003485 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003486 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3487 mirror::DexCache* dex_cache = dex_caches->Get(i);
3488 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3489 for (int32_t j = 0; j < types->GetLength(); j++) {
3490 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003491 if (klass != nullptr) {
3492 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003493 const char* descriptor = klass->GetDescriptor(&temp);
3494 size_t hash = Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003495 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3496 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003497 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3498 << PrettyClassAndClassLoader(klass);
3499 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003500 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003501 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003502 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003503 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003504 }
3505 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003506 }
3507 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003508 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003509}
3510
3511mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003512 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003513 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3514 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3515 mirror::DexCache* dex_cache = dex_caches->Get(i);
3516 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003517 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003518 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003519 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003520 const DexFile::TypeId* type_id =
3521 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003522 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003523 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3524 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003525 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003526 return klass;
3527 }
3528 }
3529 }
3530 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003531 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003532}
3533
3534void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3535 result.clear();
3536 if (dex_cache_image_class_lookup_required_) {
3537 MoveImageClassesToClassTable();
3538 }
3539 size_t hash = Hash(descriptor);
3540 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003541 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003542 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003543 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003544 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003545 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003546 }
3547 }
3548}
3549
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003550void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003551 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003552 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003553
Ian Rogers9ffb0392012-09-10 11:56:50 -07003554 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003555 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003556 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003557 return;
3558 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003559 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3560 return;
3561 }
jeffhao98eacac2011-09-14 16:11:53 -07003562
Ian Rogers9ffb0392012-09-10 11:56:50 -07003563 // The class might already be erroneous, for example at compile time if we attempted to verify
3564 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003565 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003566 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003567 return;
3568 }
3569
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003570 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003571 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003572 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003573 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003574 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003575 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003576 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003577 }
jeffhao98eacac2011-09-14 16:11:53 -07003578
Jeff Hao4a200f52014-04-01 14:58:49 -07003579 // Skip verification if disabled.
3580 if (!Runtime::Current()->IsVerificationEnabled()) {
3581 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003582 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003583 return;
3584 }
3585
Ian Rogers9ffb0392012-09-10 11:56:50 -07003586 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003587 StackHandleScope<2> hs(self);
3588 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003589 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003590 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003591 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003592
3593 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003594 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003595 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003596 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003597 std::string error_msg(
3598 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3599 PrettyDescriptor(klass.Get()).c_str(),
3600 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003601 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003602 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3603 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003604 self->ClearException();
3605 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003606 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3607 if (cause.Get() != nullptr) {
3608 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003609 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003610 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003611 if (Runtime::Current()->IsCompiler()) {
3612 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3613 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003614 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003615 return;
3616 }
3617 }
3618
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003619 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003620 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003621 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003622 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003623 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003624 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003625 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003626 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003627 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3628 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003629 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003630 return;
3631 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003632 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003633 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003634 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003635 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003636 Runtime::Current()->IsCompiler(),
3637 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003638 }
3639 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003640 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003641 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003642 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3643 << " because: " << error_msg;
3644 }
Ian Rogers1f539342012-10-03 21:09:42 -07003645 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003646 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003647 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003648 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003649 // Even though there were no verifier failures we need to respect whether the super-class
3650 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003651 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003652 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003653 } else {
3654 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003655 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003656 // Pretend a soft failure occured so that we don't consider the class verified below.
3657 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003658 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003659 } else {
3660 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3661 // Soft failures at compile time should be retried at runtime. Soft
3662 // failures at runtime will be handled by slow paths in the generated
3663 // code. Set status accordingly.
3664 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003665 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003666 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003667 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003668 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3669 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003670 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003671 }
3672 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003673 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003674 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003675 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3676 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003677 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003678 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003679 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003680 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003681 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003682 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003683 // Let the interpreter know it by setting the kAccPreverified flag onto each
3684 // method.
3685 // Note: we're going here during compilation and at runtime. When we set the
3686 // kAccPreverified flag when compiling image classes, the flag is recorded
3687 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003688 EnsurePreverifiedMethods(klass);
3689 }
3690}
3691
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003692void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003693 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003694 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003695 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003696 }
jeffhao98eacac2011-09-14 16:11:53 -07003697}
3698
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003699bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3700 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003701 // If we're compiling, we can only verify the class using the oat file if
3702 // we are not compiling the image or if the class we're verifying is not part of
3703 // the app. In other words, we will only check for preverification of bootclasspath
3704 // classes.
3705 if (Runtime::Current()->IsCompiler()) {
3706 // Are we compiling the bootclasspath?
3707 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3708 return false;
3709 }
3710 // We are compiling an app (not the image).
3711
3712 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003713 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003714 return false;
3715 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003716 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003717
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003718 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003719 // In case we run without an image there won't be a backing oat file.
3720 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003721 return false;
3722 }
3723
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003724 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003725 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003726 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3727 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003728 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003729 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003730 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003731 // Compile time verification failed with a soft error. Compile time verification can fail
3732 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003733 // class ... {
3734 // Foo x;
3735 // .... () {
3736 // if (...) {
3737 // v1 gets assigned a type of resolved class Foo
3738 // } else {
3739 // v1 gets assigned a type of unresolved class Bar
3740 // }
3741 // iput x = v1
3742 // } }
3743 // when we merge v1 following the if-the-else it results in Conflict
3744 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3745 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3746 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3747 // at compile time).
3748 return false;
3749 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003750 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003751 // Compile time verification failed with a hard error. This is caused by invalid instructions
3752 // in the class. These errors are unrecoverable.
3753 return false;
3754 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003755 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003756 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3757 // not loading the class.
3758 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3759 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003760 return false;
3761 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003762 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003763 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003764 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003765 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003766
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003767 return false;
3768}
3769
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003770void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003771 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003772 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3773 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3774 }
3775 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3776 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3777 }
3778}
3779
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003780void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003781 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003782 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3783 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003784 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003785 return; // native or abstract method
3786 }
3787 if (code_item->tries_size_ == 0) {
3788 return; // nothing to process
3789 }
3790 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
3791 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3792 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3793 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3794 CatchHandlerIterator iterator(handlers_ptr);
3795 for (; iterator.HasNext(); iterator.Next()) {
3796 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3797 // unresolved exception types will be ignored by exception delivery
3798 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003799 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003800 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003801 DCHECK(Thread::Current()->IsExceptionPending());
3802 Thread::Current()->ClearException();
3803 }
3804 }
3805 }
3806 handlers_ptr = iterator.EndDataPointer();
3807 }
3808}
3809
Brian Carlstromea46f952013-07-30 01:26:50 -07003810static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003811static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3812 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003813
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003814mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003815 jobjectArray interfaces, jobject loader,
3816 jobjectArray methods, jobjectArray throws) {
3817 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003818 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003819 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003820 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003821 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003822 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003823 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003824 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003825 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003826 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003827 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3828 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003829 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003830 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003831 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003832 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003833 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003834 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003835
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003836 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003837 {
3838 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003839 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003840 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003841 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003842 }
3843 klass->SetSFields(sfields);
3844 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003845 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3846 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003847 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3848 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003849 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003850 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003851 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003852 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003853 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003854 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003855 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3856 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003857 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3858 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003859 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003860 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003861 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003862 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003863 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003864 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003865 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003866
Ian Rogers466bb252011-10-14 03:29:56 -07003867 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003868 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003869 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003870 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003871 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003872 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003873 }
3874 klass->SetDirectMethods(directs);
3875 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003876 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003877 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003878 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003879 }
3880 klass->SetDirectMethod(0, constructor);
3881 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003882
Mathieu Chartier590fee92013-09-13 13:46:47 -07003883 // Create virtual method using specified prototypes.
3884 size_t num_virtual_methods =
3885 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003886 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003887 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3888 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003889 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003890 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003891 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003892 }
3893 klass->SetVirtualMethods(virtuals);
3894 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003895 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003896 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003897 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3898 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003899 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003900 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003901 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003902 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003903 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003904 }
3905 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003906 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003907
3908 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003909 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003910 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003911
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003912 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3913 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003914 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003915 // Must hold lock on object when resolved.
3916 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003917 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003918 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003919 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003920 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003921 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003922 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003923 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003924 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003925
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003926 CHECK(klass->IsRetired());
3927 CHECK_NE(klass.Get(), new_class);
3928 klass.Assign(new_class);
3929
3930 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003931 interfaces_sfield->SetObject<false>(klass.Get(),
3932 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003933 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003934 throws_sfield->SetObject<false>(klass.Get(),
3935 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003936
3937 {
3938 // Lock on klass is released. Lock new class object.
3939 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003940 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003941 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003942
3943 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003944 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003945 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003946 CheckProxyConstructor(klass->GetDirectMethod(0));
3947 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003948 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003949 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3950 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003951 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003952 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3953 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003954 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003955
Mathieu Chartier590fee92013-09-13 13:46:47 -07003956 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003957 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003958 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003959 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3960
3961 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003962 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003963 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003964
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003965 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003966 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003967 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003968 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003969 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003970 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003971 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003972 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003973}
3974
Ian Rogersef7d42f2014-01-06 12:55:46 -08003975std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003976 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003977 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003978 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003979 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3980}
3981
Ian Rogersef7d42f2014-01-06 12:55:46 -08003982mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3983 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003984 DCHECK(proxy_class->IsProxyClass());
3985 DCHECK(proxy_method->IsProxyMethod());
3986 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003987 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003988 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003989 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003990 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003991 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003992 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003993 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003994 break;
3995 }
3996 }
3997 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003998 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003999 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07004000 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07004001 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08004002 return resolved_method;
4003}
4004
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004005
Brian Carlstromea46f952013-07-30 01:26:50 -07004006mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004007 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07004008 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07004009 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07004010 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004011 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07004012 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
4013 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02004014 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4015 // constructor method.
4016 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
4017 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07004018 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4019 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07004020 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
4021 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004022 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07004023 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004024 }
Ian Rogers466bb252011-10-14 03:29:56 -07004025 // Make this constructor public and fix the class to be our Proxy version
4026 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004027 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004028 return constructor;
4029}
4030
Brian Carlstromea46f952013-07-30 01:26:50 -07004031static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004032 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004033 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004034 CHECK_STREQ(constructor->GetName(), "<init>");
4035 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4036 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004037 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004038}
4039
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004040mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004041 Handle<mirror::Class> klass,
4042 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004043 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4044 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004045 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004046 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004047 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004048 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004049 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004050 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004051 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004052 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004053 }
Ian Rogers466bb252011-10-14 03:29:56 -07004054
4055 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4056 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004057 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004058 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004059
Ian Rogers466bb252011-10-14 03:29:56 -07004060 // At runtime the method looks like a reference and argument saving method, clone the code
4061 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004062 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4063 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004064 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004065
Ian Rogersc2b44472011-12-14 21:17:17 -08004066 return method;
4067}
Jesse Wilson95caa792011-10-12 18:14:17 -04004068
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004069static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4070 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004071 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004072 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004073 CHECK(!prototype->IsFinal());
4074 CHECK(method->IsFinal());
4075 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004076
4077 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4078 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4079 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004080 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4081 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004082 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4083
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004084 StackHandleScope<2> hs(Thread::Current());
4085 MethodHelper mh(hs.NewHandle(method.Get()));
4086 MethodHelper mh2(hs.NewHandle(prototype.Get()));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004087 CHECK_STREQ(method->GetName(), prototype->GetName());
4088 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004089 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08004090 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004091}
4092
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004093static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4094 bool can_init_parents)
4095 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004096 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004097 return true;
4098 }
4099 if (!can_init_statics) {
4100 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004101 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004102 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004103 return false;
4104 }
4105 // Check if there are encoded static values needing initialization.
4106 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004107 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004108 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004109 if (dex_class_def->static_values_off_ != 0) {
4110 return false;
4111 }
4112 }
4113 }
4114 if (!klass->IsInterface() && klass->HasSuperClass()) {
4115 mirror::Class* super_class = klass->GetSuperClass();
4116 if (!can_init_parents && !super_class->IsInitialized()) {
4117 return false;
4118 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004119 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004120 return false;
4121 }
4122 }
4123 }
4124 return true;
4125}
4126
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004127bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004128 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004129 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4130
4131 // Are we already initialized and therefore done?
4132 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4133 // an initialized class will never change its state.
4134 if (klass->IsInitialized()) {
4135 return true;
4136 }
4137
4138 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004139 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004140 return false;
4141 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004142
Ian Rogers7b078e82014-09-10 14:44:24 -07004143 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004144 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004145 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004146 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004147
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004148 // Re-check under the lock in case another thread initialized ahead of us.
4149 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004150 return true;
4151 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004152
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004153 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004154 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004155 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004156 return false;
4157 }
4158
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004159 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004160
4161 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004162 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004163 if (!klass->IsVerified()) {
4164 // We failed to verify, expect either the klass to be erroneous or verification failed at
4165 // compile time.
4166 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004167 CHECK(self->IsExceptionPending());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004168 } else {
4169 CHECK(Runtime::Current()->IsCompiler());
4170 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004171 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004172 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004173 } else {
4174 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004175 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004176 }
4177
Brian Carlstromd1422f82011-09-28 11:37:09 -07004178 // If the class is kStatusInitializing, either this thread is
4179 // initializing higher up the stack or another thread has beat us
4180 // to initializing and we need to wait. Either way, this
4181 // invocation of InitializeClass will not be responsible for
4182 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004183 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004184 // Could have got an exception during verification.
4185 if (self->IsExceptionPending()) {
4186 return false;
4187 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004188 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004189 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004190 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004191 return true;
4192 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004193 // No. That's fine. Wait for another thread to finish initializing.
4194 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004195 }
4196
4197 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004198 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004199 return false;
4200 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004201 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004202
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004203 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004204
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004205 // From here out other threads may observe that we're initializing and so changes of state
4206 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004207 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004208 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004209
4210 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004211 }
4212
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004213 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004214 if (!klass->IsInterface() && klass->HasSuperClass()) {
4215 mirror::Class* super_class = klass->GetSuperClass();
4216 if (!super_class->IsInitialized()) {
4217 CHECK(!super_class->IsInterface());
4218 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004219 StackHandleScope<1> hs(self);
4220 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004221 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004222 if (!super_initialized) {
4223 // The super class was verified ahead of entering initializing, we should only be here if
4224 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004225 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004226 << "Super class initialization failed for "
4227 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004228 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004229 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004230 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004231 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004232 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004233 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004234 return false;
4235 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004236 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004237 }
4238
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004239 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004240 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004241 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004242 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004243 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004244 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004245 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004246 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4247 this, *dex_class_def);
4248 const byte* class_data = dex_file.GetClassData(*dex_class_def);
4249 ClassDataItemIterator field_it(dex_file, class_data);
4250 if (value_it.HasNext()) {
4251 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004252 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004253 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004254 StackHandleScope<1> hs(self);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004255 Handle<mirror::ArtField> field(hs.NewHandle(
4256 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004257 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004258 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004259 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004260 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004261 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004262 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004263 }
4264 }
4265 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004266
Ian Rogersd91d6d62013-09-25 20:26:14 -07004267 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004268 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004269 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004270 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004271 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004272 }
4273
Ian Rogers7b078e82014-09-10 14:44:24 -07004274 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004275 uint64_t t1 = NanoTime();
4276
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004277 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004278 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004279 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004280
4281 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07004282 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004283 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004284 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004285 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004286 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4287 RuntimeStats* thread_stats = self->GetStats();
4288 ++global_stats->class_init_count;
4289 ++thread_stats->class_init_count;
4290 global_stats->class_init_time_ns += (t1 - t0);
4291 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004292 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004293 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004294 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004295 std::string temp;
4296 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004297 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004298 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004299 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004300 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004301 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004302 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004303 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004304}
4305
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004306bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004307 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004308 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004309 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004310 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004311 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004312 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004313
4314 // When we wake up, repeat the test for init-in-progress. If
4315 // there's an exception pending (only possible if
4316 // "interruptShouldThrow" was set), bail out.
4317 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07004318 WrapExceptionInInitializer();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004319 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004320 return false;
4321 }
4322 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004323 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004324 continue;
4325 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004326 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004327 // Compile time initialization failed.
4328 return false;
4329 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004330 if (klass->IsErroneous()) {
4331 // The caller wants an exception, but it was thrown in a
4332 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004333 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004334 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004335 return false;
4336 }
4337 if (klass->IsInitialized()) {
4338 return true;
4339 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004340 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004341 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004342 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004343 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get());
Brian Carlstromd1422f82011-09-28 11:37:09 -07004344}
4345
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004346bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004347 if (klass->IsInterface()) {
4348 return true;
4349 }
Ian Rogers151f2212014-05-06 11:27:27 -07004350 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004351 StackHandleScope<2> hs(Thread::Current());
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004352 MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4353 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004354 if (klass->HasSuperClass() &&
4355 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004356 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4357 mh.ChangeMethod(klass->GetVTableEntry(i));
4358 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004359 if (mh.GetMethod() != super_mh.GetMethod() &&
4360 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4361 ThrowLinkageError(klass.Get(),
4362 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004363 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004364 PrettyMethod(mh.GetMethod()).c_str(),
4365 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004366 return false;
4367 }
4368 }
4369 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004370 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004371 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4372 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4373 for (uint32_t j = 0; j < num_methods; ++j) {
4374 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4375 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004376 if (mh.GetMethod() != super_mh.GetMethod() &&
4377 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4378 ThrowLinkageError(klass.Get(),
4379 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004380 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004381 PrettyMethod(mh.GetMethod()).c_str(),
4382 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004383 return false;
4384 }
4385 }
4386 }
4387 }
4388 return true;
4389}
4390
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004391bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4392 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004393 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004394 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004395 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004396 return true;
4397 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004398 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004399 if (!success) {
4400 if (can_init_fields && can_init_parents) {
4401 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4402 }
4403 } else {
4404 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004405 }
4406 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004407}
4408
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004409void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4410 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4411 if (fields != nullptr) {
4412 for (int index = 0; index < fields->GetLength(); index ++) {
4413 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4414 fields->Get(index)->SetDeclaringClass(new_class);
4415 }
4416 }
4417 }
4418
4419 fields = new_class->GetSFields();
4420 if (fields != nullptr) {
4421 for (int index = 0; index < fields->GetLength(); index ++) {
4422 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4423 fields->Get(index)->SetDeclaringClass(new_class);
4424 }
4425 }
4426 }
4427
4428 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4429 if (methods != nullptr) {
4430 for (int index = 0; index < methods->GetLength(); index ++) {
4431 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4432 methods->Get(index)->SetDeclaringClass(new_class);
4433 }
4434 }
4435 }
4436
4437 methods = new_class->GetVirtualMethods();
4438 if (methods != nullptr) {
4439 for (int index = 0; index < methods->GetLength(); index ++) {
4440 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4441 methods->Get(index)->SetDeclaringClass(new_class);
4442 }
4443 }
4444 }
4445}
4446
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004447bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4448 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004449 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004450 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004451
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004452 if (!LinkSuperClass(klass)) {
4453 return false;
4454 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004455 if (!LinkMethods(self, klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004456 return false;
4457 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004458 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004459 return false;
4460 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004461 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004462 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004463 return false;
4464 }
4465 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004466 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004467
4468 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4469 // We don't need to retire this class as it has no embedded tables or it was created the
4470 // correct size during class linker initialization.
4471 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4472
4473 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4474 klass->PopulateEmbeddedImtAndVTable();
4475 }
4476
4477 // This will notify waiters on klass that saw the not yet resolved
4478 // class in the class_table_ during EnsureResolved.
4479 klass->SetStatus(mirror::Class::kStatusResolved, self);
4480 *new_class = klass.Get();
4481 } else {
4482 CHECK(!klass->IsResolved());
4483 // Retire the temporary class and create the correctly sized resolved class.
4484 *new_class = klass->CopyOf(self, class_size);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004485 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004486 CHECK(self->IsExceptionPending()); // Expect an OOME.
4487 klass->SetStatus(mirror::Class::kStatusError, self);
4488 return false;
4489 }
4490
4491 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4492 StackHandleScope<1> hs(self);
4493 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4494 ObjectLock<mirror::Class> lock(self, new_class_h);
4495
4496 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4497
4498 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004499 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004500
4501 // This will notify waiters on temp class that saw the not yet resolved class in the
4502 // class_table_ during EnsureResolved.
4503 klass->SetStatus(mirror::Class::kStatusRetired, self);
4504
4505 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4506 // This will notify waiters on new_class that saw the not yet resolved
4507 // class in the class_table_ during EnsureResolved.
4508 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004509 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004510 return true;
4511}
4512
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004513bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004514 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004515 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4516 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004517 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004518 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004519 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004520 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004521 return false;
4522 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004523 // Verify
4524 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004525 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004526 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004527 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004528 return false;
4529 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004530 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004531 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004532 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004533 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004534 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004535 for (size_t i = 0; i < interfaces->Size(); i++) {
4536 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004537 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004538 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004539 DCHECK(Thread::Current()->IsExceptionPending());
4540 return false;
4541 }
4542 // Verify
4543 if (!klass->CanAccess(interface)) {
4544 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004545 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004546 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004547 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004548 return false;
4549 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004550 }
4551 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004552 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004553 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004554 return true;
4555}
4556
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004557bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004558 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004559 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004560 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004561 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004562 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004563 return false;
4564 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004565 return true;
4566 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004567 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004568 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4569 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004570 return false;
4571 }
4572 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004573 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004574 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %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(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004577 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004578 return false;
4579 }
4580 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004581 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004582 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004583 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004584 return false;
4585 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004586
Brian Carlstromf3632832014-05-20 15:36:53 -07004587 // Inherit kAccClassIsFinalizable from the superclass in case this
4588 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004589 if (super->IsFinalizable()) {
4590 klass->SetFinalizable();
4591 }
4592
Elliott Hughes2da50362011-10-10 16:57:08 -07004593 // Inherit reference flags (if any) from the superclass.
4594 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4595 if (reference_flags != 0) {
4596 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4597 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004598 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004599 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004600 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004601 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004602 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004603 return false;
4604 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004605
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004606 if (kIsDebugBuild) {
4607 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004608 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004609 CHECK(super->IsResolved());
4610 super = super->GetSuperClass();
4611 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004612 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004613 return true;
4614}
4615
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004616// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004617bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
4618 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004619 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004620 if (klass->IsInterface()) {
4621 // No vtable.
4622 size_t count = klass->NumVirtualMethods();
4623 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004624 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004625 return false;
4626 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004627 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004628 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004629 }
jeffhaobdb76512011-09-07 11:43:16 -07004630 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004631 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004632 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07004633 // Link virtual and interface method tables
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004634 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004635 }
4636 return true;
4637}
4638
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004639bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004640 if (klass->HasSuperClass()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004641 uint32_t max_count = klass->NumVirtualMethods() +
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004642 klass->GetSuperClass()->GetVTableLength();
4643 size_t actual_count = klass->GetSuperClass()->GetVTableLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004644 CHECK_LE(actual_count, max_count);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004645 StackHandleScope<4> hs(self);
4646 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004647 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004648 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4649 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4650 if (UNLIKELY(vtable.Get() == nullptr)) {
4651 CHECK(self->IsExceptionPending()); // OOME.
4652 return false;
4653 }
4654 int len = super_class->GetVTableLength();
Mingyao Yang1a128582014-07-22 17:33:25 -07004655 for (int i = 0; i < len; i++) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004656 vtable->Set<false>(i, super_class->GetVTableEntry(i));
4657 }
4658 } else {
Mingyao Yang38eecb02014-08-13 14:51:03 -07004659 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004660 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4661 if (UNLIKELY(vtable.Get() == nullptr)) {
4662 CHECK(self->IsExceptionPending()); // OOME.
4663 return false;
4664 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004665 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004666
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004667 // See if any of our virtual methods override the superclass.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004668 MutableMethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4669 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004670 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004671 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004672 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004673 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004674 for (; j < actual_count; ++j) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004675 mirror::ArtMethod* super_method = vtable->Get(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004676 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004677 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004678 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4679 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004680 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004681 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004682 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004683 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004684 return false;
4685 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004686 vtable->Set<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004687 local_method->SetMethodIndex(j);
4688 break;
4689 } else {
4690 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4691 << " would have incorrectly overridden the package-private method in "
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004692 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004693 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004694 }
4695 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004696 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004697 // Not overriding, append.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004698 vtable->Set<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004699 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004700 actual_count += 1;
4701 }
4702 }
4703 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004704 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004705 return false;
4706 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004707 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004708 CHECK_LE(actual_count, max_count);
4709 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004710 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004711 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004712 CHECK(self->IsExceptionPending()); // OOME.
4713 return false;
4714 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004715 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004716 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004717 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004718 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004719 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004720 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004721 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004722 return false;
4723 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004724 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004725 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004726 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004727 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004728 CHECK(self->IsExceptionPending()); // OOME.
4729 return false;
4730 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004731 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004732 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004733 vtable->Set<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004734 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004735 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004736 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004737 }
4738 return true;
4739}
4740
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004741bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass,
4742 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004743 Thread* const self = Thread::Current();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004744 Runtime* const runtime = Runtime::Current();
Jeff Hao88474b42013-10-23 16:24:40 -07004745 // Set the imt table to be all conflicts by default.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004746 klass->SetImTable(runtime->GetDefaultImt());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004747 size_t super_ifcount;
4748 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004749 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004750 } else {
4751 super_ifcount = 0;
4752 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07004753 uint32_t num_interfaces =
4754 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4755 size_t ifcount = super_ifcount + num_interfaces;
4756 for (size_t i = 0; i < num_interfaces; i++) {
4757 mirror::Class* interface =
4758 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4759 interfaces->Get(i);
4760 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004761 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004762 if (ifcount == 0) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004763 // Class implements no interfaces.
4764 DCHECK_EQ(klass->GetIfTableCount(), 0);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004765 DCHECK(klass->GetIfTable() == nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004766 return true;
4767 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004768 if (ifcount == super_ifcount) {
4769 // Class implements same interfaces as parent, are any of these not marker interfaces?
4770 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004771 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Ian Rogers9bc81912012-10-11 21:43:36 -07004772 for (size_t i = 0; i < ifcount; ++i) {
4773 if (super_iftable->GetMethodArrayCount(i) > 0) {
4774 has_non_marker_interface = true;
4775 break;
4776 }
4777 }
4778 if (!has_non_marker_interface) {
4779 // Class just inherits marker interfaces from parent so recycle parent's iftable.
4780 klass->SetIfTable(super_iftable);
4781 return true;
4782 }
4783 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004784 StackHandleScope<5> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004785 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004786 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004787 CHECK(self->IsExceptionPending()); // OOME.
4788 return false;
4789 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004790 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004791 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004792 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004793 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004794 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004795 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004796 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004797 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004798 // Flatten the interface inheritance hierarchy.
4799 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004800 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004801 mirror::Class* interface =
Mathieu Chartierf8322842014-05-16 10:59:25 -07004802 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4803 interfaces->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004804 DCHECK(interface != nullptr);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004805 if (!interface->IsInterface()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004806 std::string temp;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004807 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4808 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers1ff3c982014-08-12 02:30:58 -07004809 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004810 return false;
4811 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004812 // Check if interface is already in iftable
4813 bool duplicate = false;
4814 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004815 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004816 if (existing_interface == interface) {
4817 duplicate = true;
4818 break;
4819 }
4820 }
4821 if (!duplicate) {
4822 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004823 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004824 // Add this interface's non-duplicate super-interfaces.
4825 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004826 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004827 bool super_duplicate = false;
4828 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004829 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004830 if (existing_interface == super_interface) {
4831 super_duplicate = true;
4832 break;
4833 }
4834 }
4835 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004836 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004837 }
4838 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004839 }
4840 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004841 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004842 // Shrink iftable in case duplicates were found
4843 if (idx < ifcount) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004844 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004845 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004846 CHECK(self->IsExceptionPending()); // OOME.
4847 return false;
4848 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004849 ifcount = idx;
4850 } else {
4851 CHECK_EQ(idx, ifcount);
4852 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004853 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004854
4855 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004856 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004857 return true;
4858 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004859 self->AllowThreadSuspension();
Jeff Hao88474b42013-10-23 16:24:40 -07004860 // Allocate imtable
4861 bool imtable_changed = false;
Ian Rogers700a4022014-05-19 16:49:03 -07004862 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004863 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004864 if (UNLIKELY(imtable.Get() == nullptr)) {
Jeff Hao88474b42013-10-23 16:24:40 -07004865 CHECK(self->IsExceptionPending()); // OOME.
4866 return false;
4867 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004868 MutableMethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4869 MutableMethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004870 size_t max_miranda_methods = 0; // The max size of miranda_list.
4871 for (size_t i = 0; i < ifcount; ++i) {
4872 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4873 }
4874 Handle<mirror::ObjectArray<mirror::ArtMethod>>
4875 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
4876 size_t miranda_list_size = 0; // The current size of miranda_list.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004877 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004878 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004879 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004880 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004881 StackHandleScope<2> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004882 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004883 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4884 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004885 CHECK(self->IsExceptionPending()); // OOME.
4886 return false;
4887 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004888 iftable->SetMethodArray(i, method_array.Get());
Ian Rogers700a4022014-05-19 16:49:03 -07004889 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004890 hs.NewHandle(klass->GetVTableDuringLinking()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004891 for (size_t j = 0; j < num_methods; ++j) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004892 interface_mh.ChangeMethod(iftable->GetInterface(i)->GetVirtualMethod(j));
Ian Rogers9bc81912012-10-11 21:43:36 -07004893 int32_t k;
4894 // For each method listed in the interface's method list, find the
4895 // matching method in our class's method list. We want to favor the
4896 // subclass over the superclass, which just requires walking
4897 // back from the end of the vtable. (This only matters if the
4898 // superclass defines a private method and this class redefines
4899 // it -- otherwise it would use the same vtable slot. In .dex files
4900 // those don't end up in the virtual method table, so it shouldn't
4901 // matter which direction we go. We walk it backward anyway.)
4902 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004903 vtable_mh.ChangeMethod(vtable->Get(k));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004904 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004905 if (!vtable_mh.Get()->IsAbstract() && !vtable_mh.Get()->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004906 ThrowIllegalAccessError(
4907 klass.Get(),
4908 "Method '%s' implementing interface method '%s' is not public",
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004909 PrettyMethod(vtable_mh.Get()).c_str(),
4910 PrettyMethod(interface_mh.Get()).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004911 return false;
4912 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004913 method_array->Set<false>(j, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004914 // Place method in imt if entry is empty, place conflict otherwise.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004915 uint32_t imt_index = interface_mh.Get()->GetDexMethodIndex() % mirror::Class::kImtSize;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004916 if (imtable->Get(imt_index) == nullptr) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004917 imtable->Set<false>(imt_index, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004918 imtable_changed = true;
4919 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004920 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -07004921 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004922 break;
4923 }
4924 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004925 if (k < 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004926 StackHandleScope<1> hs(self);
4927 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004928 for (size_t l = 0; l < miranda_list_size; ++l) {
4929 mirror::ArtMethod* mir_method = miranda_list->Get(l);
4930 DCHECK(mir_method != nullptr);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004931 vtable_mh.ChangeMethod(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004932 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004933 miranda_method.Assign(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004934 break;
4935 }
4936 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004937 if (miranda_method.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004938 // Point the interface table at a phantom slot.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004939 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_mh.Get()->Clone(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004940 if (UNLIKELY(miranda_method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004941 CHECK(self->IsExceptionPending()); // OOME.
4942 return false;
4943 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004944 DCHECK_LT(miranda_list_size, max_miranda_methods);
4945 miranda_list->Set<false>(miranda_list_size++, miranda_method.Get());
Ian Rogers9bc81912012-10-11 21:43:36 -07004946 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004947 method_array->Set<false>(j, miranda_method.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004948 }
4949 }
4950 }
4951 }
Jeff Hao88474b42013-10-23 16:24:40 -07004952 if (imtable_changed) {
4953 // Fill in empty entries in interface method table with conflict.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004954 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004955 for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004956 if (imtable->Get(i) == nullptr) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004957 imtable->Set<false>(i, imt_conflict_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004958 }
4959 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004960 klass->SetImTable(imtable.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004961 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004962 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004963 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004964 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004965 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4966 if (old_method_count == 0) {
4967 virtuals = AllocArtMethodArray(self, new_method_count);
4968 } else {
4969 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4970 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004971 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004972 CHECK(self->IsExceptionPending()); // OOME.
4973 return false;
4974 }
4975 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004976
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004977 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004978 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004979 hs.NewHandle(klass->GetVTableDuringLinking()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004980 CHECK(vtable.Get() != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004981 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004982 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004983 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004984 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004985 CHECK(self->IsExceptionPending()); // OOME.
4986 return false;
4987 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004988 for (size_t i = 0; i < miranda_list_size; ++i) {
4989 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004990 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004991 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4992 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4993 klass->SetVirtualMethod(old_method_count + i, method);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004994 vtable->Set<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004995 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004996 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004997 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004998 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004999
Brian Carlstromea46f952013-07-30 01:26:50 -07005000 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07005001 for (int i = 0; i < vtable->GetLength(); ++i) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005002 CHECK(vtable->Get(i) != nullptr);
Elliott Hughes4681c802011-09-25 18:04:37 -07005003 }
5004
Ian Rogers7b078e82014-09-10 14:44:24 -07005005 self->AllowThreadSuspension();
Elliott Hughes4681c802011-09-25 18:04:37 -07005006
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005007 return true;
5008}
5009
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005010bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005011 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005012 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005013}
5014
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005015bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005016 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005017 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005018}
5019
Brian Carlstromdbc05252011-09-09 01:59:59 -07005020struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005021 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5022 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005023 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005024 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005025 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005026 // 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 -07005027 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5028 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005029 if (type1 != type2) {
5030 bool is_primitive1 = type1 != Primitive::kPrimNot;
5031 bool is_primitive2 = type2 != Primitive::kPrimNot;
Fred Shih37f05ef2014-07-16 18:38:08 -07005032 if (type1 != type2) {
5033 if (is_primitive1 && is_primitive2) {
5034 // Larger primitive types go first.
5035 return Primitive::ComponentSize(type1) > Primitive::ComponentSize(type2);
5036 } else {
5037 // Reference always goes first.
5038 return !is_primitive1;
5039 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08005040 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005041 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005042 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005043 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005044 }
5045};
5046
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005047bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005048 size_t* class_size) {
5049 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005050 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005051 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005052
Brian Carlstromea46f952013-07-30 01:26:50 -07005053 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005054 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005055
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005056 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005057 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005058 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005059 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
5060 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
5061 // Static fields come after the embedded tables.
5062 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
Fred Shih37f05ef2014-07-16 18:38:08 -07005063 0, 0, 0, 0, 0);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005064 }
5065 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005066 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005067 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005068 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005069 CHECK(super_class->IsResolved())
5070 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005071 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005072 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005073 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005074
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005075 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005076
Brian Carlstromdbc05252011-09-09 01:59:59 -07005077 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005078 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005079 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005080 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005081 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005082 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005083 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005084 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005085 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005086 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005087 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5088 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005089
Fred Shih381e4ca2014-08-25 17:24:27 -07005090 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005091 size_t current_field = 0;
5092 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005093 FieldGaps gaps;
5094
Brian Carlstromdbc05252011-09-09 01:59:59 -07005095 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005096 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005097 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005098 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005099 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005100 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005101 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005102 if (UNLIKELY(!IsAligned<4>(field_offset.Uint32Value()))) {
5103 MemberOffset old_offset = field_offset;
5104 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5105 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5106 }
5107 DCHECK(IsAligned<4>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005108 grouped_and_sorted_fields.pop_front();
5109 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005110 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005111 field->SetOffset(field_offset);
5112 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005113 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005114 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5115 // otherwise we could end up with suboptimal gap fills.
5116 ShuffleForward<8>(num_fields, &current_field, &field_offset,
5117 fields, &grouped_and_sorted_fields, &gaps);
5118 ShuffleForward<4>(num_fields, &current_field, &field_offset,
5119 fields, &grouped_and_sorted_fields, &gaps);
5120 ShuffleForward<2>(num_fields, &current_field, &field_offset,
5121 fields, &grouped_and_sorted_fields, &gaps);
5122 ShuffleForward<1>(num_fields, &current_field, &field_offset,
5123 fields, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005124 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5125 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005126 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005127
Elliott Hughesadb460d2011-10-05 17:02:34 -07005128 // 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 -07005129 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005130 // We know there are no non-reference fields in the Reference classes, and we know
5131 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005132 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005133 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005134 --num_reference_fields;
5135 }
5136
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005137 if (kIsDebugBuild) {
5138 // Make sure that all reference fields appear before
5139 // non-reference fields, and all double-wide fields are aligned.
5140 bool seen_non_ref = false;
5141 for (size_t i = 0; i < num_fields; i++) {
5142 mirror::ArtField* field = fields->Get(i);
5143 if (false) { // enable to debug field layout
5144 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005145 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005146 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07005147 << " offset="
5148 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005149 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005150 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005151 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005152 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005153 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005154 is_primitive = true; // We lied above, so we have to expect a lie here.
5155 }
5156 if (is_primitive) {
5157 if (!seen_non_ref) {
5158 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07005159 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005160 }
5161 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07005162 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005163 }
5164 }
5165 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005166 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005167 }
5168 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005169
5170 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005171 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005172 if (is_static) {
5173 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005174 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005175 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005176 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005177 if (!klass->IsVariableSize()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005178 std::string temp;
5179 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005180 size_t previous_size = klass->GetObjectSize();
5181 if (previous_size != 0) {
5182 // Make sure that we didn't originally have an incorrect size.
Ian Rogers1ff3c982014-08-12 02:30:58 -07005183 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005184 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005185 klass->SetObjectSize(size);
5186 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005187 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005188 return true;
5189}
5190
5191// Set the bitmap of reference offsets, refOffsets, from the ifields
5192// list.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005193void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005194 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005195 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005196 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005197 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07005198 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005199 if (reference_offsets == CLASS_WALK_SUPER) {
5200 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005201 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005202 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005203 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005204 CreateReferenceOffsets(klass, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005205}
5206
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005207void ClassLinker::CreateReferenceOffsets(Handle<mirror::Class> klass,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005208 uint32_t reference_offsets) {
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005209 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
5210 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07005211 // All of the fields that contain object references are guaranteed
5212 // to be at the beginning of the fields list.
5213 for (size_t i = 0; i < num_reference_fields; ++i) {
5214 // Note that byte_offset is the offset from the beginning of
5215 // object, not the offset into instance data
Ian Rogersef7d42f2014-01-06 12:55:46 -08005216 mirror::ArtField* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005217 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005218 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
5219 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
5220 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07005221 CHECK_NE(new_bit, 0U);
5222 reference_offsets |= new_bit;
5223 } else {
5224 reference_offsets = CLASS_WALK_SUPER;
5225 break;
5226 }
5227 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005228 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005229}
5230
Mathieu Chartier590fee92013-09-13 13:46:47 -07005231mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005232 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005233 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005234 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005235 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005236 return resolved;
5237 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005238 uint32_t utf16_length;
5239 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005240 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005241 dex_cache->SetResolvedString(string_idx, string);
5242 return string;
5243}
5244
Mathieu Chartier590fee92013-09-13 13:46:47 -07005245mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005246 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005247 StackHandleScope<2> hs(Thread::Current());
5248 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5249 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005250 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5251}
5252
5253mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005254 Handle<mirror::DexCache> dex_cache,
5255 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005256 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005257 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005258 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005259 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005260 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005261 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005262 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005263 // TODO: we used to throw here if resolved's class loader was not the
5264 // boot class loader. This was to permit different classes with the
5265 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005266 dex_cache->SetResolvedType(type_idx, resolved);
5267 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005268 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005269 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005270 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005271 StackHandleScope<1> hs(self);
5272 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005273 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005274 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005275 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005276 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005277 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005278 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005279 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005280 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005281 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005282 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005283 return resolved;
5284}
5285
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005286mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005287 Handle<mirror::DexCache> dex_cache,
5288 Handle<mirror::ClassLoader> class_loader,
5289 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005290 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005291 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005292 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005293 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005294 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005295 return resolved;
5296 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005297 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005298 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005299 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005300 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005301 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005302 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005303 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005304 // Scan using method_idx, this saves string compares but will only hit for matching dex
5305 // caches/files.
5306 switch (type) {
5307 case kDirect: // Fall-through.
5308 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005309 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005310 break;
5311 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005312 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005313 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005314 break;
5315 case kSuper: // Fall-through.
5316 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005317 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005318 break;
5319 default:
5320 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005321 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005322 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005323 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005324 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005325 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005326 switch (type) {
5327 case kDirect: // Fall-through.
5328 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005329 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005330 break;
5331 case kInterface:
5332 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005333 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005334 break;
5335 case kSuper: // Fall-through.
5336 case kVirtual:
5337 resolved = klass->FindVirtualMethod(name, signature);
5338 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005339 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005340 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005341 // If we found a method, check for incompatible class changes.
5342 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005343 // Be a good citizen and update the dex cache to speed subsequent calls.
5344 dex_cache->SetResolvedMethod(method_idx, resolved);
5345 return resolved;
5346 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005347 // If we had a method, it's an incompatible-class-change error.
5348 if (resolved != nullptr) {
5349 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5350 } else {
5351 // We failed to find the method which means either an access error, an incompatible class
5352 // change, or no such method. First try to find the method among direct and virtual methods.
5353 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5354 const Signature signature = dex_file.GetMethodSignature(method_id);
5355 switch (type) {
5356 case kDirect:
5357 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005358 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005359 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5360 // have had a resolved method before, which triggers the "true" branch above.
5361 break;
5362 case kInterface:
5363 case kVirtual:
5364 case kSuper:
5365 resolved = klass->FindDirectMethod(name, signature);
5366 break;
5367 }
5368
5369 // If we found something, check that it can be accessed by the referrer.
5370 if (resolved != nullptr && referrer.Get() != nullptr) {
5371 mirror::Class* methods_class = resolved->GetDeclaringClass();
5372 mirror::Class* referring_class = referrer->GetDeclaringClass();
5373 if (!referring_class->CanAccess(methods_class)) {
5374 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5375 resolved, type);
5376 return nullptr;
5377 } else if (!referring_class->CanAccessMember(methods_class,
5378 resolved->GetAccessFlags())) {
5379 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5380 return nullptr;
5381 }
5382 }
5383
5384 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5385 // methods and throw if we find the method there. If we find nothing, throw a
5386 // NoSuchMethodError.
5387 switch (type) {
5388 case kDirect:
5389 case kStatic:
5390 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005391 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005392 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005393 resolved = klass->FindInterfaceMethod(name, signature);
5394 if (resolved != nullptr) {
5395 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5396 } else {
5397 ThrowNoSuchMethodError(type, klass, name, signature);
5398 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005399 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005400 break;
5401 case kInterface:
5402 if (resolved != nullptr) {
5403 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005404 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005405 resolved = klass->FindVirtualMethod(name, signature);
5406 if (resolved != nullptr) {
5407 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5408 } else {
5409 ThrowNoSuchMethodError(type, klass, name, signature);
5410 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005411 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005412 break;
5413 case kSuper:
Andreas Gampedf733752014-08-25 20:55:01 -07005414 if (resolved != nullptr) {
5415 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5416 } else {
5417 ThrowNoSuchMethodError(type, klass, name, signature);
5418 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005419 break;
5420 case kVirtual:
5421 if (resolved != nullptr) {
5422 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5423 } else {
5424 resolved = klass->FindInterfaceMethod(name, signature);
5425 if (resolved != nullptr) {
5426 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5427 } else {
5428 ThrowNoSuchMethodError(type, klass, name, signature);
5429 }
5430 }
5431 break;
5432 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005433 }
5434 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005435 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005436 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005437}
5438
Mathieu Chartier590fee92013-09-13 13:46:47 -07005439mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005440 Handle<mirror::DexCache> dex_cache,
5441 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005442 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005443 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005444 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005445 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005446 return resolved;
5447 }
5448 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005449 Thread* const self = Thread::Current();
5450 StackHandleScope<1> hs(self);
5451 Handle<mirror::Class> klass(
5452 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005453 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005454 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005455 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005456 }
5457
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005458 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005459 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005460 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005461 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005462 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005463
Andreas Gampe58a5af82014-07-31 16:23:49 -07005464 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005465 const char* name = dex_file.GetFieldName(field_id);
5466 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5467 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005468 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005469 } else {
5470 resolved = klass->FindInstanceField(name, type);
5471 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005472 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005473 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005474 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005475 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005476 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005477 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005478 return resolved;
5479}
5480
Brian Carlstromea46f952013-07-30 01:26:50 -07005481mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005482 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005483 Handle<mirror::DexCache> dex_cache,
5484 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005485 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005486 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005487 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005488 return resolved;
5489 }
5490 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005491 Thread* self = Thread::Current();
5492 StackHandleScope<1> hs(self);
5493 Handle<mirror::Class> klass(
5494 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005495 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005496 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005497 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005498 }
5499
Ian Rogersdfb325e2013-10-30 01:00:44 -07005500 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5501 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005502 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005503 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005504 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005505 dex_cache->SetResolvedField(field_idx, resolved);
5506 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005507 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005508 }
5509 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005510}
5511
Brian Carlstromea46f952013-07-30 01:26:50 -07005512const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005513 uint32_t* length) {
5514 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5515 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005516 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005517 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005518 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005519}
5520
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005521void ClassLinker::DumpAllClasses(int flags) {
5522 if (dex_cache_image_class_lookup_required_) {
5523 MoveImageClassesToClassTable();
5524 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005525 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5526 // 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 -08005527 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005528 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005529 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005530 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5531 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005532 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005533 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005534 }
5535
5536 for (size_t i = 0; i < all_classes.size(); ++i) {
5537 all_classes[i]->DumpClass(std::cerr, flags);
5538 }
5539}
5540
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005541void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005542 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005543 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005544 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005545 MoveImageClassesToClassTable();
5546 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005547 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005548 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005549}
5550
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005551size_t ClassLinker::NumLoadedClasses() {
5552 if (dex_cache_image_class_lookup_required_) {
5553 MoveImageClassesToClassTable();
5554 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005555 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005556 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005557}
5558
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005559pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005560 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005561}
5562
5563pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005564 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005565}
5566
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005567void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005568 DCHECK(!init_done_);
5569
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005570 DCHECK(klass != nullptr);
5571 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005572
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005573 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005574 DCHECK(class_roots != nullptr);
5575 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005576 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005577}
5578
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005579} // namespace art