blob: b380fed16cef6bb63171299fc4d37e244a7da5fb [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070020#include <iostream>
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070022#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
Andreas Gampea696c0a2014-12-10 20:51:45 -080024#include <unistd.h>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027
Mathieu Chartierc7853442015-03-27 14:35:38 -070028#include "art_field-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080030#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010031#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080032#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080033#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000035#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080036#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070037#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070038#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070039#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "gc/accounting/card_table-inl.h"
41#include "gc/accounting/heap_bitmap.h"
42#include "gc/heap.h"
43#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070044#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070045#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070046#include "interpreter/interpreter.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080047#include "jit/jit.h"
48#include "jit/jit_code_cache.h"
Ian Rogers0571d352011-11-03 19:51:38 -070049#include "leb128.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070050#include "linear_alloc.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080051#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070052#include "oat_file.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080053#include "oat_file_assistant.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070054#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070055#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/class.h"
57#include "mirror/class-inl.h"
58#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070059#include "mirror/dex_cache-inl.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070060#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080061#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080062#include "mirror/object-inl.h"
63#include "mirror/object_array-inl.h"
64#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070065#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080066#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070067#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080068#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070069#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070070#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070071#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070072#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070073#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070074#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070075#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080076#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070077#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070078
79namespace art {
80
Mathieu Chartierc7853442015-03-27 14:35:38 -070081static constexpr bool kSanityCheckObjects = kIsDebugBuild;
82
Ian Rogers00f7d0e2012-07-19 15:28:27 -070083static void ThrowNoClassDefFoundError(const char* fmt, ...)
84 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070085 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070086static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070087 va_list args;
88 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080089 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +000090 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080091 va_end(args);
92}
93
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080094static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070095 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070096 // The class failed to initialize on a previous attempt, so we want to throw
97 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
98 // failed in verification, in which case v2 5.4.1 says we need to re-throw
99 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800100 Runtime* const runtime = Runtime::Current();
101 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -0700102 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
103 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700104
Elliott Hughes5c599942012-06-13 16:45:05 -0700105 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800106 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800107 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700108 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
109 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000110 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700111 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700112 if (c->GetVerifyErrorClass() != NULL) {
113 // TODO: change the verifier to store an _instance_, with a useful detail message?
114 std::string temp;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000115 self->ThrowNewException(c->GetVerifyErrorClass()->GetDescriptor(&temp),
Ian Rogers7b078e82014-09-10 14:44:24 -0700116 PrettyDescriptor(c).c_str());
117 } else {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000118 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
Ian Rogers7b078e82014-09-10 14:44:24 -0700119 PrettyDescriptor(c).c_str());
120 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700121 }
122}
123
Brian Carlstromb23eab12014-10-08 17:55:21 -0700124static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
125 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
126 if (VLOG_IS_ON(class_linker)) {
127 std::string temp;
128 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000129 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700130 }
131}
132
133static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
134 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700135 Thread* self = Thread::Current();
136 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700137
138 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700139 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700140
141 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700142 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
143 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700144
Elliott Hughesa4f94742012-05-29 16:28:38 -0700145 // We only wrap non-Error exceptions; an Error can just be used as-is.
146 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000147 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700148 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700149 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700150}
151
Fred Shih381e4ca2014-08-25 17:24:27 -0700152// Gap between two fields in object layout.
153struct FieldGap {
154 uint32_t start_offset; // The offset from the start of the object.
155 uint32_t size; // The gap size of 1, 2, or 4 bytes.
156};
157struct FieldGapsComparator {
158 explicit FieldGapsComparator() {
159 }
160 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
161 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800162 // Sort by gap size, largest first. Secondary sort by starting offset.
163 return lhs.size > rhs.size || (lhs.size == rhs.size && lhs.start_offset < rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700164 }
165};
166typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
167
168// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800169static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700170 DCHECK(gaps != nullptr);
171
172 uint32_t current_offset = gap_start;
173 while (current_offset != gap_end) {
174 size_t remaining = gap_end - current_offset;
175 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
176 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
177 current_offset += sizeof(uint32_t);
178 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
179 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
180 current_offset += sizeof(uint16_t);
181 } else {
182 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
183 current_offset += sizeof(uint8_t);
184 }
185 DCHECK_LE(current_offset, gap_end) << "Overran gap";
186 }
187}
188// Shuffle fields forward, making use of gaps whenever possible.
189template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000190static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700191 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700192 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700193 FieldGaps* gaps)
194 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
195 DCHECK(current_field_idx != nullptr);
196 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700197 DCHECK(gaps != nullptr);
198 DCHECK(field_offset != nullptr);
199
200 DCHECK(IsPowerOfTwo(n));
201 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700202 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700203 Primitive::Type type = field->GetTypeAsPrimitiveType();
204 if (Primitive::ComponentSize(type) < n) {
205 break;
206 }
207 if (!IsAligned<n>(field_offset->Uint32Value())) {
208 MemberOffset old_offset = *field_offset;
209 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
210 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
211 }
212 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
213 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700214 if (!gaps->empty() && gaps->top().size >= n) {
215 FieldGap gap = gaps->top();
216 gaps->pop();
217 DCHECK(IsAligned<n>(gap.start_offset));
218 field->SetOffset(MemberOffset(gap.start_offset));
219 if (gap.size > n) {
220 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
221 }
222 } else {
223 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
224 field->SetOffset(*field_offset);
225 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
226 }
227 ++(*current_field_idx);
228 }
229}
230
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800231ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700232 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700233 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700234 dex_cache_image_class_lookup_required_(false),
235 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800236 class_roots_(nullptr),
237 array_iftable_(nullptr),
238 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700239 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800240 log_new_dex_caches_roots_(false),
241 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700242 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800243 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800244 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100245 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800246 quick_to_interpreter_bridge_trampoline_(nullptr),
247 image_pointer_size_(sizeof(void*)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700248 CHECK(intern_table_ != nullptr);
249 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
250 find_array_class_cache_[i] = GcRoot<mirror::Class>(nullptr);
251 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700252}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700253
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800254void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800255 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700256 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700257
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700258 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700259
Elliott Hughes30646832011-10-13 16:59:46 -0700260 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700261 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700262 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700263 // 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 -0800264 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700265 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
266 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700267 heap->AllocNonMovableObject<true>(self, nullptr,
268 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700269 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700270 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700271 mirror::Class::SetClassClass(java_lang_Class.Get());
272 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700273 if (kUseBakerOrBrooksReadBarrier) {
274 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800275 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700276 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700277 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800278 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800279 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700280
Elliott Hughes418d20f2011-09-22 14:00:39 -0700281 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700282 Handle<mirror::Class> class_array_class(hs.NewHandle(
283 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700284 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700285
Ian Rogers23435d02012-09-24 11:23:12 -0700286 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700287 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
288 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700289 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700290 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700291 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700292 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700293
Ian Rogers23435d02012-09-24 11:23:12 -0700294 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700295 Handle<mirror::Class> object_array_class(hs.NewHandle(
296 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700297 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700298
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700299 // Setup the char (primitive) class to be used for char[].
300 Handle<mirror::Class> char_class(hs.NewHandle(
301 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700302 // The primitive char class won't be initialized by
303 // InitializePrimitiveClass until line 459, but strings (and
304 // internal char arrays) will be allocated before that and the
305 // component size, which is computed from the primitive type, needs
306 // to be set here.
307 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700308
Ian Rogers23435d02012-09-24 11:23:12 -0700309 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700310 Handle<mirror::Class> char_array_class(hs.NewHandle(
311 AllocClass(self, java_lang_Class.Get(),
312 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700313 char_array_class->SetComponentType(char_class.Get());
314 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700315
Ian Rogers23435d02012-09-24 11:23:12 -0700316 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700317 Handle<mirror::Class> java_lang_String(hs.NewHandle(
318 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700319 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700320 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700321 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400322
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700323 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700324 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
325 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
326 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
327 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700328 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700329
Ian Rogers23435d02012-09-24 11:23:12 -0700330 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700331 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700332 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
333 kClassRootsMax));
334 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700335 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
336 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
337 SetClassRoot(kClassArrayClass, class_array_class.Get());
338 SetClassRoot(kObjectArrayClass, object_array_class.Get());
339 SetClassRoot(kCharArrayClass, char_array_class.Get());
340 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700341 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700342
343 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700344 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
345 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
346 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
347 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
348 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
349 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
350 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
351 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700352
Ian Rogers23435d02012-09-24 11:23:12 -0700353 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700354 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355
Ian Rogers23435d02012-09-24 11:23:12 -0700356 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700357 Handle<mirror::Class> int_array_class(hs.NewHandle(
358 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700360 mirror::IntArray::SetArrayClass(int_array_class.Get());
361 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700362
Mathieu Chartierc7853442015-03-27 14:35:38 -0700363 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
364 Handle<mirror::Class> long_array_class(hs.NewHandle(
365 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
366 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
367 mirror::LongArray::SetArrayClass(long_array_class.Get());
368 SetClassRoot(kLongArrayClass, long_array_class.Get());
369
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700370 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700371
Ian Rogers52813c92012-10-11 11:50:38 -0700372 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700373 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
374 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700375 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700376 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700377 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378
Mathieu Chartierc7853442015-03-27 14:35:38 -0700379 // Constructor, Method, and AbstractMethod are necessary so
Brian Carlstromf3632832014-05-20 15:36:53 -0700380 // that FindClass can link members.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700381
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700382 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
383 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700384 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800385 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
386 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700387 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700388 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700389 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700390
391 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700392 Handle<mirror::Class> object_array_string(hs.NewHandle(
393 AllocClass(self, java_lang_Class.Get(),
394 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700395 object_array_string->SetComponentType(java_lang_String.Get());
396 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700397
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700398 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
399 AllocClass(self, java_lang_Class.Get(),
400 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700401 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
402 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700403
Ian Rogers23435d02012-09-24 11:23:12 -0700404 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
405 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
406 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700407 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800408 for (auto& dex_file : boot_class_path) {
409 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700410 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800411 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700412 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
414 // now we can use FindSystemClass
415
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700416 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700417 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
418 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700419
Jeff Hao88474b42013-10-23 16:24:40 -0700420 // Create runtime resolution and imt conflict methods. Also setup the default imt.
421 Runtime* runtime = Runtime::Current();
422 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
423 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700424 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700425 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
426
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700427 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
428 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700429 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800430 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700431 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700432 quick_resolution_trampoline_ = GetQuickResolutionStub();
433 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
434 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700435 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700436
Mathieu Chartier66f19252012-09-18 08:57:04 -0700437 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700438 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800439 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700440 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700441 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700442 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800443 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700444 std::ostringstream os1, os2;
445 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
446 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
447 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
448 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700449 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800450 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700451 CHECK_EQ(java_lang_String.Get(), String_class);
452 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700453 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454
Ian Rogers23435d02012-09-24 11:23:12 -0700455 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800456 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800457 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458
Ian Rogers98379392014-02-24 16:53:16 -0800459 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800460 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461
Ian Rogers98379392014-02-24 16:53:16 -0800462 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700463 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464
Ian Rogers98379392014-02-24 16:53:16 -0800465 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800466 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467
Ian Rogers98379392014-02-24 16:53:16 -0800468 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700469 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470
Mathieu Chartierc7853442015-03-27 14:35:38 -0700471 mirror::Class* found_long_array_class = FindSystemClass(self, "[J");
472 CHECK_EQ(long_array_class.Get(), found_long_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700473
Ian Rogers98379392014-02-24 16:53:16 -0800474 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800475 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476
Ian Rogers98379392014-02-24 16:53:16 -0800477 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800478 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700479
Ian Rogers98379392014-02-24 16:53:16 -0800480 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700481 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700482
Ian Rogers98379392014-02-24 16:53:16 -0800483 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700484 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700485
Ian Rogers23435d02012-09-24 11:23:12 -0700486 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800487 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700488 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800489 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700490 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700491 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
492 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700493 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700494 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700495 array_iftable->SetInterface(0, java_lang_Cloneable);
496 array_iftable->SetInterface(1, java_io_Serializable);
497 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700498
Ian Rogers23435d02012-09-24 11:23:12 -0700499 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700500 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
501 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
502 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
503 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700504 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700505 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800506 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700507 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700508
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700509 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800510 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700511 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700512
Brian Carlstromf3632832014-05-20 15:36:53 -0700513 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700514 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700515 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700516
Brian Carlstromea46f952013-07-30 01:26:50 -0700517 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700518 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700519 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700520
Ian Rogers23435d02012-09-24 11:23:12 -0700521 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700522
Ian Rogers23435d02012-09-24 11:23:12 -0700523 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800524 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700525 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
526
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700527 // Create java.lang.reflect.Field.class root.
528 mirror::Class* java_lang_reflect_Field = FindSystemClass(self, "Ljava/lang/reflect/Field;");
529 CHECK(java_lang_reflect_Field != nullptr);
530 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
531 mirror::Field::SetClass(java_lang_reflect_Field);
532
533 // Create java.lang.reflect.Field array root.
534 mirror::Class* java_lang_reflect_Field_array =
535 FindSystemClass(self, "[Ljava/lang/reflect/Field;");
536 CHECK(java_lang_reflect_Field_array != nullptr);
537 SetClassRoot(kJavaLangReflectFieldArrayClass, java_lang_reflect_Field_array);
538 mirror::Field::SetArrayClass(java_lang_reflect_Field_array);
539
Brian Carlstrom1f870082011-08-23 16:02:11 -0700540 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700541 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700542 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700543 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
544 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
545 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
546 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700547 mirror::Class* java_lang_ref_FinalizerReference =
548 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700549 java_lang_ref_FinalizerReference->SetAccessFlags(
550 java_lang_ref_FinalizerReference->GetAccessFlags() |
551 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700552 mirror::Class* java_lang_ref_PhantomReference =
553 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554 java_lang_ref_PhantomReference->SetAccessFlags(
555 java_lang_ref_PhantomReference->GetAccessFlags() |
556 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700557 mirror::Class* java_lang_ref_SoftReference =
558 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 java_lang_ref_SoftReference->SetAccessFlags(
560 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700561 mirror::Class* java_lang_ref_WeakReference =
562 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700563 java_lang_ref_WeakReference->SetAccessFlags(
564 java_lang_ref_WeakReference->GetAccessFlags() |
565 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700566
Ian Rogers23435d02012-09-24 11:23:12 -0700567 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800568 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700569 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700570 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
571
jeffhao8cd6dda2012-02-22 10:15:34 -0800572 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700573 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800574 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800575 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700576 SetClassRoot(kJavaLangClassNotFoundException,
577 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800578 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700579 SetClassRoot(kJavaLangStackTraceElementArrayClass,
580 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800581 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700582
Andreas Gampe76bd8802014-12-10 16:43:58 -0800583 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
584 // initialized.
585 {
586 const DexFile& dex_file = java_lang_Object->GetDexFile();
587 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
588 CHECK(void_string_id != nullptr);
589 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
590 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
591 CHECK(void_type_id != nullptr);
592 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
593 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
594 // as referrer so the used dex cache is core's one.
595 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
596 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
597 self->AssertNoPendingException();
598 }
599
Ian Rogers98379392014-02-24 16:53:16 -0800600 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700601
Brian Carlstroma004aa92012-02-08 18:05:09 -0800602 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700603}
604
Ian Rogers98379392014-02-24 16:53:16 -0800605void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800606 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700607
608 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700609 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700610 // as the types of the field can't be resolved prior to the runtime being
611 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800612 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700613 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800614 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800615
Mathieu Chartierc7853442015-03-27 14:35:38 -0700616 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700617 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
618 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700619
Mathieu Chartierc7853442015-03-27 14:35:38 -0700620 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700621 CHECK_STREQ(queue->GetName(), "queue");
622 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700623
Mathieu Chartierc7853442015-03-27 14:35:38 -0700624 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700625 CHECK_STREQ(queueNext->GetName(), "queueNext");
626 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700627
Mathieu Chartierc7853442015-03-27 14:35:38 -0700628 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700629 CHECK_STREQ(referent->GetName(), "referent");
630 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700631
Mathieu Chartierc7853442015-03-27 14:35:38 -0700632 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700633 CHECK_STREQ(zombie->GetName(), "zombie");
634 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700635
Brian Carlstroma663ea52011-08-19 23:33:41 -0700636 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700637 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700638 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800639 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700640 CHECK(klass != nullptr);
641 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700642 // note SetClassRoot does additional validation.
643 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700644 }
645
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700646 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700647
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700648 // disable the slow paths in FindClass and CreatePrimitiveClass now
649 // that Object, Class, and Object[] are setup
650 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700651
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800652 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700653}
654
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700655void ClassLinker::RunRootClinits() {
656 Thread* self = Thread::Current();
657 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800658 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700659 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700660 StackHandleScope<1> hs(self);
661 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700662 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700663 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700664 }
665 }
666}
667
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700668const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700669 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800670 if (kIsDebugBuild) {
671 for (size_t i = 0; i < oat_files_.size(); ++i) {
672 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700673 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800674 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700675 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
676 oat_files_.push_back(oat_file);
677 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800678}
679
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700680OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
681 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700682 OatFile* oat_file = space->ReleaseOatFile();
683 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700684 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700685 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700686}
687
Richard Uhler66d874d2015-01-15 09:37:19 -0800688std::vector<std::unique_ptr<const DexFile>> ClassLinker::OpenDexFilesFromOat(
689 const char* dex_location, const char* oat_location,
690 std::vector<std::string>* error_msgs) {
691 CHECK(error_msgs != nullptr);
Calin Juravle621962a2014-09-02 15:53:55 +0100692
Richard Uhler66d874d2015-01-15 09:37:19 -0800693 // Verify we aren't holding the mutator lock, which could starve GC if we
694 // have to generate or relocate an oat file.
695 Locks::mutator_lock_->AssertNotHeld(Thread::Current());
696
697 OatFileAssistant oat_file_assistant(dex_location, oat_location, kRuntimeISA,
698 !Runtime::Current()->IsAotCompiler());
699
700 // Lock the target oat location to avoid races generating and loading the
701 // oat file.
702 std::string error_msg;
703 if (!oat_file_assistant.Lock(&error_msg)) {
704 // Don't worry too much if this fails. If it does fail, it's unlikely we
705 // can generate an oat file anyway.
706 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700707 }
708
Richard Uhler66d874d2015-01-15 09:37:19 -0800709 // Check if we already have an up-to-date oat file open.
710 const OatFile* source_oat_file = nullptr;
711 {
712 ReaderMutexLock mu(Thread::Current(), dex_lock_);
713 for (const OatFile* oat_file : oat_files_) {
714 CHECK(oat_file != nullptr);
715 if (oat_file_assistant.GivenOatFileIsUpToDate(*oat_file)) {
716 source_oat_file = oat_file;
717 break;
Andreas Gampe833a4852014-05-21 18:46:59 -0700718 }
719 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700720 }
721
Richard Uhler66d874d2015-01-15 09:37:19 -0800722 // If we didn't have an up-to-date oat file open, try to load one from disk.
723 if (source_oat_file == nullptr) {
724 // Update the oat file on disk if we can. This may fail, but that's okay.
725 // Best effort is all that matters here.
726 if (!oat_file_assistant.MakeUpToDate(&error_msg)) {
727 LOG(WARNING) << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700728 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700729
Richard Uhler66d874d2015-01-15 09:37:19 -0800730 // Get the oat file on disk.
731 std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
732 if (oat_file.get() != nullptr) {
733 source_oat_file = oat_file.release();
734 RegisterOatFile(source_oat_file);
Andreas Gampe833a4852014-05-21 18:46:59 -0700735 }
736 }
737
Richard Uhler66d874d2015-01-15 09:37:19 -0800738 std::vector<std::unique_ptr<const DexFile>> dex_files;
Andreas Gampe833a4852014-05-21 18:46:59 -0700739
Richard Uhler66d874d2015-01-15 09:37:19 -0800740 // Load the dex files from the oat file.
741 if (source_oat_file != nullptr) {
742 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
743 if (dex_files.empty()) {
744 error_msgs->push_back("Failed to open dex files from "
745 + source_oat_file->GetLocation());
Andreas Gampe833a4852014-05-21 18:46:59 -0700746 }
747 }
748
Richard Uhler66d874d2015-01-15 09:37:19 -0800749 // Fall back to running out of the original dex file if we couldn't load any
750 // dex_files from the oat file.
751 if (dex_files.empty()) {
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700752 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800753 if (!DexFile::Open(dex_location, dex_location, &error_msg, &dex_files)) {
754 LOG(WARNING) << error_msg;
755 error_msgs->push_back("Failed to open dex files from "
756 + std::string(dex_location));
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700757 }
758 } else {
759 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
760 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700761 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800762 return dex_files;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700763}
764
Brian Carlstromae826982011-11-09 01:33:42 -0800765const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700766 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700767 for (size_t i = 0; i < oat_files_.size(); i++) {
768 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700769 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -0800770 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700771 return oat_file;
772 }
773 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700774 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -0700775}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700776
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800777void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700778 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700779 DCHECK(obj != nullptr);
780 DCHECK(class_linker != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700781 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700782 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -0700783 if (!method->IsNative()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800784 const size_t pointer_size = class_linker->image_pointer_size_;
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800785 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800786 if (!method->IsRuntimeMethod() && method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800787 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
788 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -0700789 }
790 }
791 }
792}
793
Mathieu Chartierc7853442015-03-27 14:35:38 -0700794void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED)
795 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
796 DCHECK(obj != nullptr);
797 CHECK(obj->GetClass() != nullptr) << "Null class " << obj;
798 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
799 if (obj->IsClass()) {
800 auto klass = obj->AsClass();
801 ArtField* fields[2] = { klass->GetSFields(), klass->GetIFields() };
802 size_t num_fields[2] = { klass->NumStaticFields(), klass->NumInstanceFields() };
803 for (size_t i = 0; i < 2; ++i) {
804 for (size_t j = 0; j < num_fields[i]; ++j) {
805 CHECK_EQ(fields[i][j].GetDeclaringClass(), klass);
806 }
807 }
808 }
809}
810
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700811void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800812 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700813 CHECK(!init_done_);
814
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700815 Runtime* const runtime = Runtime::Current();
816 Thread* const self = Thread::Current();
817 gc::Heap* const heap = runtime->GetHeap();
818 gc::space::ImageSpace* const space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700819 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700820 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700821 OatFile& oat_file = GetImageOatFile(space);
822 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
823 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700824 const char* image_file_location = oat_file.GetOatHeader().
825 GetStoreValueByKey(OatHeader::kImageLocationKey);
826 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700827 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -0700828 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -0800829 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +0100830 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800831 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
832 mirror::ObjectArray<mirror::DexCache>* dex_caches =
833 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700834
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700835 StackHandleScope<1> hs(self);
836 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
837 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
838 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700839 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700840
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700841 // Special case of setting up the String class early so that we can test arbitrary objects
842 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700843 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800844
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700845 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700846 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700847 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800848 StackHandleScope<1> hs2(self);
849 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700850 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700851 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
852 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700853 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700854 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800855 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
856 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700857 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700858 << " from within oat file " << oat_file.GetLocation()
859 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -0800860 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700861 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -0700862
863 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
864
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800865 AppendToBootClassPath(*dex_file.get(), dex_cache);
866 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700867 }
868
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700869 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
870 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -0700871 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800872 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700873 if (!runtime->IsAotCompiler()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800874 // Aot compiler supports having an image with a different pointer size than the runtime. This
Mathieu Chartier2d721012014-11-10 11:08:06 -0800875 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
876 // also use 32 bit dex2oat on a system with 64 bit apps.
877 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
878 << sizeof(void*);
879 }
880 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
881 image_pointer_size_ = 4;
882 } else {
883 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
884 image_pointer_size_ = 8;
885 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -0700886
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700887 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800888 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700889 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700890 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700891 if (kSanityCheckObjects) {
892 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
893 auto* dex_cache = dex_caches->Get(i);
894 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
895 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
896 if (field != nullptr) {
897 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
898 }
899 }
900 }
901 heap->VisitObjects(SanityCheckObjectsCallback, nullptr);
902 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700903
904 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800905 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700906 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700907
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800908 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700909 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800910 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800911 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700912 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
913 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Fred Shih4ee7a662014-07-11 09:59:27 -0700914 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800915 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
916 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
917 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
918 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
919 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
920 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
921 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
922 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
923 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
924 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700925
Ian Rogers98379392014-02-24 16:53:16 -0800926 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700927
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800928 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700929}
930
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700931void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700932 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700933 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
934 visitor, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700935 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800936 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700937 buffered_visitor.VisitRoot(root);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700938 root.Read()->VisitFieldRoots(buffered_visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800939 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700940 // PreZygote classes can't move so we won't need to update fields' declaring classes.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800941 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700942 buffered_visitor.VisitRoot(root);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700943 root.Read()->VisitFieldRoots(buffered_visitor);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700944 }
945 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800946 for (auto& root : new_class_roots_) {
947 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700948 old_ref->VisitFieldRoots(buffered_visitor);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700949 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800950 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700951 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700952 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
953 // corresponding object. This is slow, but luckily for us, this may only happen with a
954 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800955 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800956 DCHECK(it != class_table_.end());
957 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700958 }
959 }
960 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700961 buffered_visitor.Flush(); // Flush before clearing new_class_roots_.
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700962 if ((flags & kVisitRootFlagClearRootLog) != 0) {
963 new_class_roots_.clear();
964 }
965 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
966 log_new_class_table_roots_ = true;
967 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
968 log_new_class_table_roots_ = false;
969 }
970 // We deliberately ignore the class roots in the image since we
971 // handle image roots by using the MS/CMS rescanning of dirty cards.
972}
973
Brian Carlstroma663ea52011-08-19 23:33:41 -0700974// Keep in sync with InitCallback. Anything we visit, we need to
975// reinit references to when reinitializing a ClassLinker from a
976// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700977void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
978 class_roots_.VisitRoot(visitor, RootInfo(kRootVMInternal));
979 Thread* const self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -0700980 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700981 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800982 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700983 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700984 dex_cache.VisitRoot(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700985 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800986 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
987 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700988 dex_caches_[index].VisitRoot(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -0700989 }
Elliott Hughesf8349362012-06-18 15:00:06 -0700990 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800991 if ((flags & kVisitRootFlagClearRootLog) != 0) {
992 new_dex_cache_roots_.clear();
993 }
994 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
995 log_new_dex_caches_roots_ = true;
996 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
997 log_new_dex_caches_roots_ = false;
998 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700999 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001000 VisitClassRoots(visitor, flags);
1001 array_iftable_.VisitRoot(visitor, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001002 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001003 find_array_class_cache_[i].VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001004 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001005}
1006
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001007void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1008 if (dex_cache_image_class_lookup_required_) {
1009 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001010 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001011 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001012 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001013 for (GcRoot<mirror::Class>& root : class_table_) {
1014 if (!visitor(root.Read(), arg)) {
1015 return;
1016 }
1017 }
1018 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1019 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001020 return;
1021 }
1022 }
1023}
1024
Ian Rogersdbf3be02014-08-29 15:40:08 -07001025static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001026 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001027 classes->insert(c);
1028 return true;
1029}
1030
Ian Rogersdbf3be02014-08-29 15:40:08 -07001031struct GetClassesVisitorArrayArg {
1032 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1033 int32_t index;
1034 bool success;
1035};
1036
1037static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1038 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1039 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1040 if (arg->index < (*arg->classes)->GetLength()) {
1041 (*arg->classes)->Set(arg->index, c);
1042 arg->index++;
1043 return true;
1044 } else {
1045 arg->success = false;
1046 return false;
1047 }
1048}
1049
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001050void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001051 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1052 // is avoiding duplicates.
1053 if (!kMovingClasses) {
1054 std::set<mirror::Class*> classes;
1055 VisitClasses(GetClassesVisitorSet, &classes);
1056 for (mirror::Class* klass : classes) {
1057 if (!visitor(klass, arg)) {
1058 return;
1059 }
1060 }
1061 } else {
1062 Thread* self = Thread::Current();
1063 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001064 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001065 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1066 GetClassesVisitorArrayArg local_arg;
1067 local_arg.classes = &classes;
1068 local_arg.success = false;
1069 // We size the array assuming classes won't be added to the class table during the visit.
1070 // If this assumption fails we iterate again.
1071 while (!local_arg.success) {
1072 size_t class_table_size;
1073 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001074 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001075 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001076 }
1077 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1078 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1079 classes.Assign(
1080 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1081 CHECK(classes.Get() != nullptr); // OOME.
1082 local_arg.index = 0;
1083 local_arg.success = true;
1084 VisitClasses(GetClassesVisitorArray, &local_arg);
1085 }
1086 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1087 // If the class table shrank during creation of the clases array we expect null elements. If
1088 // the class table grew then the loop repeats. If classes are created after the loop has
1089 // finished then we don't visit.
1090 mirror::Class* klass = classes->Get(i);
1091 if (klass != nullptr && !visitor(klass, arg)) {
1092 return;
1093 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001094 }
1095 }
1096}
1097
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001098ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001099 mirror::Class::ResetClass();
1100 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001101 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001102 mirror::ArtMethod::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001103 mirror::Field::ResetClass();
1104 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001105 mirror::BooleanArray::ResetArrayClass();
1106 mirror::ByteArray::ResetArrayClass();
1107 mirror::CharArray::ResetArrayClass();
1108 mirror::DoubleArray::ResetArrayClass();
1109 mirror::FloatArray::ResetArrayClass();
1110 mirror::IntArray::ResetArrayClass();
1111 mirror::LongArray::ResetArrayClass();
1112 mirror::ShortArray::ResetArrayClass();
1113 mirror::Throwable::ResetClass();
1114 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001115 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001116}
1117
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001118mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001119 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001120 StackHandleScope<16> hs(self);
1121 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1122 Handle<mirror::DexCache> dex_cache(
1123 hs.NewHandle(down_cast<mirror::DexCache*>(
1124 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1125 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001126 if (dex_cache.Get() == nullptr) {
1127 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001128 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001129 Handle<mirror::String>
1130 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001131 if (location.Get() == nullptr) {
1132 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001133 }
Ian Rogers700a4022014-05-19 16:49:03 -07001134 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001135 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001136 if (strings.Get() == nullptr) {
1137 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001138 }
Ian Rogers700a4022014-05-19 16:49:03 -07001139 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001140 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001141 if (types.Get() == nullptr) {
1142 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001143 }
Ian Rogers700a4022014-05-19 16:49:03 -07001144 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001145 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001146 if (methods.Get() == nullptr) {
1147 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001148 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001149 Handle<mirror::Array> fields;
1150 if (image_pointer_size_ == 8) {
1151 fields = hs.NewHandle<mirror::Array>(mirror::LongArray::Alloc(self, dex_file.NumFieldIds()));
1152 } else {
1153 fields = hs.NewHandle<mirror::Array>(mirror::IntArray::Alloc(self, dex_file.NumFieldIds()));
1154 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001155 if (fields.Get() == nullptr) {
1156 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001157 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001158 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1159 fields.Get());
1160 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001161}
1162
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001163mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001164 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001165 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001166 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001167 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001168 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001169 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1170 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001171 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001172 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001173 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001174 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001175 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001176}
1177
Ian Rogers6fac4472014-02-25 17:01:10 -08001178mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001179 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001180}
1181
Brian Carlstromea46f952013-07-30 01:26:50 -07001182mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001183 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001184 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001185}
1186
Mathieu Chartier590fee92013-09-13 13:46:47 -07001187mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1188 Thread* self, size_t length) {
1189 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1190 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001191}
1192
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001193mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1194 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001195 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001196
1197 // For temporary classes we must wait for them to be retired.
1198 if (init_done_ && klass->IsTemp()) {
1199 CHECK(!klass->IsResolved());
1200 if (klass->IsErroneous()) {
1201 ThrowEarlierClassFailure(klass);
1202 return nullptr;
1203 }
1204 StackHandleScope<1> hs(self);
1205 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1206 ObjectLock<mirror::Class> lock(self, h_class);
1207 // Loop and wait for the resolving thread to retire this class.
1208 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1209 lock.WaitIgnoringInterrupts();
1210 }
1211 if (h_class->IsErroneous()) {
1212 ThrowEarlierClassFailure(h_class.Get());
1213 return nullptr;
1214 }
1215 CHECK(h_class->IsRetired());
1216 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001217 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
1218 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001219 }
1220
Brian Carlstromaded5f72011-10-07 17:15:04 -07001221 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001222 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001223 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001224 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1225 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001226 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001227 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1228 ThrowClassCircularityError(h_class.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001229 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001230 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001231 }
1232 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001233 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001234 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001235 }
1236 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001237
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001238 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001239 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001240 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001241 }
1242 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001243 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001244 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001245 return klass;
1246}
1247
Ian Rogers68b56852014-08-29 20:19:11 -07001248typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1249
1250// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001251ClassPathEntry FindInClassPath(const char* descriptor,
1252 size_t hash, const std::vector<const DexFile*>& class_path) {
1253 for (const DexFile* dex_file : class_path) {
1254 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001255 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07001256 return ClassPathEntry(dex_file, dex_class_def);
1257 }
1258 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001259 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001260}
1261
Andreas Gampef865ea92015-04-13 22:14:19 -07001262static bool IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1263 mirror::ClassLoader* class_loader)
1264 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1265 return class_loader == nullptr ||
1266 class_loader->GetClass() ==
1267 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader);
1268}
1269
1270bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1271 Thread* self, const char* descriptor,
1272 size_t hash,
1273 Handle<mirror::ClassLoader> class_loader,
1274 mirror::Class** result) {
1275 // Termination case: boot class-loader.
1276 if (IsBootClassLoader(soa, class_loader.Get())) {
1277 // The boot class loader, search the boot class path.
1278 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
1279 if (pair.second != nullptr) {
1280 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
1281 if (klass != nullptr) {
1282 *result = EnsureResolved(self, descriptor, klass);
1283 } else {
1284 *result = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(),
1285 *pair.first, *pair.second);
1286 }
1287 if (*result == nullptr) {
1288 CHECK(self->IsExceptionPending()) << descriptor;
1289 self->ClearException();
1290 }
Ian Rogers32427292014-11-19 14:05:21 -08001291 } else {
Andreas Gampef865ea92015-04-13 22:14:19 -07001292 *result = nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001293 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001294 return true;
1295 }
1296
1297 // Unsupported class-loader?
1298 if (class_loader->GetClass() !=
1299 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) {
1300 *result = nullptr;
1301 return false;
1302 }
1303
1304 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
1305 StackHandleScope<4> hs(self);
1306 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
1307 bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result);
1308
1309 if (!recursive_result) {
1310 // Something wrong up the chain.
1311 return false;
1312 }
1313
1314 if (*result != nullptr) {
1315 // Found the class up the chain.
1316 return true;
1317 }
1318
1319 // Handle this step.
1320 // Handle as if this is the child PathClassLoader.
1321 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1322 // We need to get the DexPathList and loop through it.
1323 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
1324 ArtField* const dex_file_field =
1325 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
1326 mirror::Object* dex_path_list =
1327 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1328 GetObject(class_loader.Get());
1329 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
1330 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1331 mirror::Object* dex_elements_obj =
1332 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1333 GetObject(dex_path_list);
1334 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1335 // at the mCookie which is a DexFile vector.
1336 if (dex_elements_obj != nullptr) {
1337 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1338 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1339 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1340 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1341 if (element == nullptr) {
1342 // Should never happen, fall back to java code to throw a NPE.
1343 break;
1344 }
1345 mirror::Object* dex_file = dex_file_field->GetObject(element);
1346 if (dex_file != nullptr) {
1347 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1348 if (long_array == nullptr) {
1349 // This should never happen so log a warning.
1350 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001351 break;
1352 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001353 int32_t long_array_size = long_array->GetLength();
1354 for (int32_t j = 0; j < long_array_size; ++j) {
1355 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1356 long_array->GetWithoutChecks(j)));
1357 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
1358 if (dex_class_def != nullptr) {
1359 RegisterDexFile(*cp_dex_file);
1360 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
1361 *cp_dex_file, *dex_class_def);
1362 if (klass == nullptr) {
1363 CHECK(self->IsExceptionPending()) << descriptor;
1364 self->ClearException();
1365 // TODO: Is it really right to break here, and not check the other dex files?
1366 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001367 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001368 *result = klass;
1369 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001370 }
1371 }
1372 }
1373 }
1374 }
Ian Rogers32427292014-11-19 14:05:21 -08001375 self->AssertNoPendingException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001376 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001377
1378 // Result is still null from the parent call, no need to set it again...
1379 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001380}
1381
Ian Rogers98379392014-02-24 16:53:16 -08001382mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001383 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001384 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001385 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001386 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001387 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001388 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1389 // for primitive classes that aren't backed by dex files.
1390 return FindPrimitiveClass(descriptor[0]);
1391 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001392 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001393 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001394 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001395 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001396 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001397 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001398 // Class is not yet loaded.
1399 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001400 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001401 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001402 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001403 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001404 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001405 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001406 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001407 } else {
1408 // The boot class loader is searched ahead of the application class loader, failures are
1409 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1410 // trigger the chaining with a proper stack trace.
1411 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001412 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001413 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001414 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001415 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001416 ScopedObjectAccessUnchecked soa(self);
Andreas Gampef865ea92015-04-13 22:14:19 -07001417 mirror::Class* cp_klass;
1418 if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) {
1419 // The chain was understood. So the value in cp_klass is either the class we were looking
1420 // for, or not found.
1421 if (cp_klass != nullptr) {
1422 return cp_klass;
1423 }
1424 // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this
1425 // and the branch above. TODO: throw the right exception here.
1426
1427 // We'll let the Java-side rediscover all this and throw the exception with the right stack
1428 // trace.
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001429 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001430
1431 if (Runtime::Current()->IsAotCompiler()) {
1432 // Oops, compile-time, can't run actual class-loader code.
1433 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
1434 self->SetException(pre_allocated);
1435 return nullptr;
1436 }
1437
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001438 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001439 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001440 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001441 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001442 {
1443 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001444 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1445 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001446 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001447 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001448 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001449 }
Ian Rogers68b56852014-08-29 20:19:11 -07001450 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001451 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1452 WellKnownClasses::java_lang_ClassLoader_loadClass,
1453 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001454 }
Ian Rogers98379392014-02-24 16:53:16 -08001455 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001456 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001457 return nullptr;
1458 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001459 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001460 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
1461 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001462 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001463 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001464 // success, return mirror::Class*
1465 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001466 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001467 }
Ian Rogers07140832014-09-30 15:43:59 -07001468 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001469}
1470
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001471mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001472 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001473 const DexFile& dex_file,
1474 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001475 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001476 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001477
Brian Carlstromaded5f72011-10-07 17:15:04 -07001478 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001479 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001480 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001481 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001482 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001483 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001484 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001485 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001486 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001487 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1488 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001489 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001490 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001491 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001492 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001493 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001494 }
1495
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001496 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001497 // Allocate a class with the status of not ready.
1498 // Interface object should get the right size here. Regular class will
1499 // figure out the right size later and be replaced with one of the right
1500 // size when the class becomes resolved.
1501 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001502 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001503 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001504 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001505 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001506 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001507 klass->SetDexCache(FindDexCache(dex_file));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001508
1509 SetupClass(dex_file, dex_class_def, klass, class_loader.Get());
1510
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001511 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001512 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001513
Mathieu Chartier590fee92013-09-13 13:46:47 -07001514 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001515 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001516 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001517 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1518 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001519 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001520 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001521
Mathieu Chartierc7853442015-03-27 14:35:38 -07001522 // Load the fields and other things after we are inserted in the table. This is so that we don't
1523 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
1524 // other reason is that the field roots are only visited from the class table. So we need to be
1525 // inserted before we allocate / fill in these fields.
1526 LoadClass(self, dex_file, dex_class_def, klass);
1527 if (self->IsExceptionPending()) {
1528 // An exception occured during load, set status to erroneous while holding klass' lock in case
1529 // notification is necessary.
1530 if (!klass->IsErroneous()) {
1531 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
1532 }
1533 return nullptr;
1534 }
1535
Brian Carlstromaded5f72011-10-07 17:15:04 -07001536 // Finish loading (if necessary) by finding parents
1537 CHECK(!klass->IsLoaded());
1538 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1539 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001540 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001541 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001542 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001543 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001544 }
1545 CHECK(klass->IsLoaded());
1546 // Link the class (if necessary)
1547 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001548 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001549 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001550
1551 mirror::Class* new_class = nullptr;
1552 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001553 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001554 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001555 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001556 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001557 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001558 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001559 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001560 CHECK(new_class != nullptr) << descriptor;
1561 CHECK(new_class->IsResolved()) << descriptor;
1562
1563 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001564
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001565 // Instrumentation may have updated entrypoints for all methods of all
1566 // classes. However it could not update methods of this class while we
1567 // were loading it. Now the class is resolved, we can update entrypoints
1568 // as required by instrumentation.
1569 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1570 // We must be in the kRunnable state to prevent instrumentation from
1571 // suspending all threads to update entrypoints while we are doing it
1572 // for this class.
1573 DCHECK_EQ(self->GetState(), kRunnable);
1574 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
1575 }
1576
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001577 /*
1578 * We send CLASS_PREPARE events to the debugger from here. The
1579 * definition of "preparation" is creating the static fields for a
1580 * class and initializing them to the standard default values, but not
1581 * executing any code (that comes later, during "initialization").
1582 *
1583 * We did the static preparation in LinkClass.
1584 *
1585 * The class has been prepared and resolved but possibly not yet verified
1586 * at this point.
1587 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001588 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001589
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001590 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001591}
1592
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001593uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1594 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001595 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001596 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001597 size_t num_8 = 0;
1598 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001599 size_t num_32 = 0;
1600 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001601 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001602 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1603 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001604 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001605 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001606 switch (c) {
1607 case 'L':
1608 case '[':
1609 num_ref++;
1610 break;
1611 case 'J':
1612 case 'D':
1613 num_64++;
1614 break;
1615 case 'I':
1616 case 'F':
1617 num_32++;
1618 break;
1619 case 'S':
1620 case 'C':
1621 num_16++;
1622 break;
1623 case 'B':
1624 case 'Z':
1625 num_8++;
1626 break;
1627 default:
1628 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001629 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001630 }
1631 }
1632 }
Fred Shih37f05ef2014-07-16 18:38:08 -07001633 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001634}
1635
Ian Rogers97b52f82014-08-14 11:34:07 -07001636OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
1637 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001638 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Richard Uhler07b3c232015-03-31 15:57:54 -07001639 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001640 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001641 *found = false;
1642 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001643 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001644 *found = true;
1645 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001646}
1647
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001648static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
1649 uint32_t method_idx) {
1650 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001651 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001652 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001653 ClassDataItemIterator it(dex_file, class_data);
1654 // Skip fields
1655 while (it.HasNextStaticField()) {
1656 it.Next();
1657 }
1658 while (it.HasNextInstanceField()) {
1659 it.Next();
1660 }
1661 // Process methods
1662 size_t class_def_method_index = 0;
1663 while (it.HasNextDirectMethod()) {
1664 if (it.GetMemberIndex() == method_idx) {
1665 return class_def_method_index;
1666 }
1667 class_def_method_index++;
1668 it.Next();
1669 }
1670 while (it.HasNextVirtualMethod()) {
1671 if (it.GetMemberIndex() == method_idx) {
1672 return class_def_method_index;
1673 }
1674 class_def_method_index++;
1675 it.Next();
1676 }
1677 DCHECK(!it.HasNext());
1678 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001679 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001680}
1681
Ian Rogers97b52f82014-08-14 11:34:07 -07001682const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001683 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001684 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001685 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001686 size_t oat_method_index;
1687 if (method->IsStatic() || method->IsDirect()) {
1688 // Simple case where the oat method index was stashed at load time.
1689 oat_method_index = method->GetMethodIndex();
1690 } else {
1691 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1692 // by search for its position in the declared virtual methods.
1693 oat_method_index = declaring_class->NumDirectMethods();
1694 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001695 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001696 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001697 // Check method index instead of identity in case of duplicate method definitions.
1698 if (method->GetDexMethodIndex() ==
1699 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001700 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001701 break;
1702 }
Ian Rogersf320b632012-03-13 18:47:47 -07001703 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001704 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001705 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1706 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001707 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001708 DCHECK_EQ(oat_method_index,
1709 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001710 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001711 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001712 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1713 declaring_class->GetDexClassDefIndex(),
1714 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001715 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001716 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001717 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001718 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001719}
1720
1721// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001722const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001723 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001724 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001725 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001726 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001727 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001728 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1729 if (found) {
1730 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001731 if (code != nullptr) {
1732 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001733 }
1734 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001735 jit::Jit* const jit = Runtime::Current()->GetJit();
1736 if (jit != nullptr) {
1737 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001738 if (code != nullptr) {
1739 return code;
1740 }
1741 }
1742 if (method->IsNative()) {
1743 // No code and native? Use generic trampoline.
1744 return GetQuickGenericJniStub();
1745 }
1746 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001747}
1748
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001749const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
1750 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1751 return nullptr;
1752 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001753 bool found;
1754 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1755 if (found) {
1756 return oat_method.GetQuickCode();
1757 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001758 jit::Jit* jit = Runtime::Current()->GetJit();
1759 if (jit != nullptr) {
1760 auto* code = jit->GetCodeCache()->GetCodeFor(method);
1761 if (code != nullptr) {
1762 return code;
1763 }
1764 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001765 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001766}
1767
Ian Rogersef7d42f2014-01-06 12:55:46 -08001768const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1769 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001770 bool found;
1771 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
1772 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001773 return nullptr;
1774 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001775 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001776 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001777}
1778
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001779// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001780static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07001781 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001782 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001783 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08001784 // May return true for native code, in the case of generic JNI
1785 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001786 return true;
1787 }
1788 // If interpreter mode is enabled, every method (except native and proxy) must
1789 // be run with interpreter.
1790 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1791 !method->IsNative() && !method->IsProxyMethod();
1792}
1793
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001794void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08001795 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07001796 if (klass->NumDirectMethods() == 0) {
1797 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08001798 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001799 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001800 if (!runtime->IsStarted()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001801 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001802 return; // OAT file unavailable.
1803 }
Ian Rogers19846512012-02-24 11:42:47 -08001804 }
Alex Light64ad14d2014-08-19 14:23:13 -07001805
Mathieu Chartierf8322842014-05-16 10:59:25 -07001806 const DexFile& dex_file = klass->GetDexFile();
1807 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07001808 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07001809 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07001810 // There should always be class data if there were direct methods.
1811 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08001812 ClassDataItemIterator it(dex_file, class_data);
1813 // Skip fields
1814 while (it.HasNextStaticField()) {
1815 it.Next();
1816 }
1817 while (it.HasNextInstanceField()) {
1818 it.Next();
1819 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001820 bool has_oat_class;
1821 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1822 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07001823 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001824 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001825 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001826 if (!method->IsStatic()) {
1827 // Only update static methods.
1828 continue;
Ian Rogers19846512012-02-24 11:42:47 -08001829 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001830 const void* quick_code = nullptr;
1831 if (has_oat_class) {
1832 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001833 quick_code = oat_method.GetQuickCode();
1834 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001835 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001836 if (enter_interpreter) {
1837 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07001838 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001839 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001840 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08001841 } else {
1842 quick_code = GetQuickToInterpreterBridge();
1843 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001844 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001845 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08001846 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001847 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08001848}
1849
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001850void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07001851 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001852 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001853 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001854 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001855 // The following code only applies to a non-compiler runtime.
1856 return;
1857 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001858 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001859 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001860 if (oat_class != nullptr) {
1861 // Every kind of method should at least get an invoke stub from the oat_method.
1862 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001863 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001864 oat_method.LinkMethod(method.Get());
1865 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001866
Jeff Hao16743632013-05-08 10:59:04 -07001867 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001868 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08001869 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001870 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001871 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001872 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07001873 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001874 }
1875
Brian Carlstrom92827a52011-10-10 15:50:01 -07001876 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001877 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001878 return;
1879 }
Ian Rogers19846512012-02-24 11:42:47 -08001880
1881 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001882 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001883 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
1884 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001885 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001886 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001887 if (!method->IsNative()) {
1888 // Set entry point from compiled code if there's no code or in interpreter only mode.
1889 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001890 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001891 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001892 }
Ian Rogers0d6de042012-02-29 08:50:26 -08001893 }
jeffhao26c0a1a2012-01-17 16:28:33 -08001894
Ian Rogers62d6c772013-02-27 08:32:07 -08001895 if (method->IsNative()) {
1896 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001897 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07001898
1899 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001900 // We have a native method here without code. Then it should have either the generic JNI
1901 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
1902 // TODO: this doesn't handle all the cases where trampolines may be installed.
1903 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1904 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07001905 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001906 }
1907}
1908
Mathieu Chartierc7853442015-03-27 14:35:38 -07001909void ClassLinker::SetupClass(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1910 Handle<mirror::Class> klass, mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001911 CHECK(klass.Get() != nullptr);
1912 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001913 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001914 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001915 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001916
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001917 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07001918 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07001919 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001920 klass->SetAccessFlags(access_flags);
1921 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001922 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001923 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001924
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001925 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001926 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08001927 CHECK(klass->GetDexCacheStrings() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001928}
Brian Carlstrom934486c2011-07-12 23:42:50 -07001929
Mathieu Chartierc7853442015-03-27 14:35:38 -07001930void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
1931 const DexFile::ClassDef& dex_class_def,
1932 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07001933 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001934 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001935 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001936 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001937 bool has_oat_class = false;
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001938 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001939 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1940 &has_oat_class);
1941 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001942 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07001943 }
1944 }
1945 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001946 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001947 }
1948}
1949
Mathieu Chartierc7853442015-03-27 14:35:38 -07001950ArtField* ClassLinker::AllocArtFieldArray(Thread* self, size_t length) {
1951 auto* const la = Runtime::Current()->GetLinearAlloc();
1952 auto* ptr = reinterpret_cast<ArtField*>(la->AllocArray<ArtField>(self, length));
1953 CHECK(ptr!= nullptr);
1954 std::uninitialized_fill_n(ptr, length, ArtField());
1955 return ptr;
1956}
1957
Ian Rogers7b078e82014-09-10 14:44:24 -07001958void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07001959 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001960 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001961 const OatFile::OatClass* oat_class) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001962 // Load static fields.
Ian Rogers0571d352011-11-03 19:51:38 -07001963 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001964 const size_t num_sfields = it.NumStaticFields();
1965 ArtField* sfields = num_sfields != 0 ? AllocArtFieldArray(self, num_sfields) : nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001966 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001967 CHECK_LT(i, num_sfields);
Ian Rogers7b078e82014-09-10 14:44:24 -07001968 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001969 LoadField(it, klass, &sfields[i]);
Ian Rogers0571d352011-11-03 19:51:38 -07001970 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001971 klass->SetSFields(sfields);
1972 klass->SetNumStaticFields(num_sfields);
1973 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
1974 // Load instance fields.
1975 const size_t num_ifields = it.NumInstanceFields();
1976 ArtField* ifields = num_ifields != 0 ? AllocArtFieldArray(self, num_ifields) : nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001977 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001978 CHECK_LT(i, num_ifields);
Ian Rogers7b078e82014-09-10 14:44:24 -07001979 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001980 LoadField(it, klass, &ifields[i]);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001981 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001982 klass->SetIFields(ifields);
1983 klass->SetNumInstanceFields(num_ifields);
1984 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001985
Ian Rogers0571d352011-11-03 19:51:38 -07001986 // Load methods.
1987 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001988 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001989 mirror::ObjectArray<mirror::ArtMethod>* directs =
1990 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001991 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001992 CHECK(self->IsExceptionPending()); // OOME.
1993 return;
1994 }
1995 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001996 }
Ian Rogers0571d352011-11-03 19:51:38 -07001997 if (it.NumVirtualMethods() != 0) {
1998 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001999 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2000 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002001 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002002 CHECK(self->IsExceptionPending()); // OOME.
2003 return;
2004 }
2005 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002006 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002007 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002008 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2009 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002010 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002011 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002012 StackHandleScope<1> hs(self);
2013 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002014 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002015 CHECK(self->IsExceptionPending()); // OOME.
2016 return;
2017 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002018 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002019 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002020 uint32_t it_method_index = it.GetMemberIndex();
2021 if (last_dex_method_index == it_method_index) {
2022 // duplicate case
2023 method->SetMethodIndex(last_class_def_method_index);
2024 } else {
2025 method->SetMethodIndex(class_def_method_index);
2026 last_dex_method_index = it_method_index;
2027 last_class_def_method_index = class_def_method_index;
2028 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002029 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002030 }
2031 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002032 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002033 StackHandleScope<1> hs(self);
2034 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002035 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002036 CHECK(self->IsExceptionPending()); // OOME.
2037 return;
2038 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002039 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002040 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002041 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002042 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002043 }
2044 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002045}
2046
Mathieu Chartierc7853442015-03-27 14:35:38 -07002047void ClassLinker::LoadField(const ClassDataItemIterator& it, Handle<mirror::Class> klass,
2048 ArtField* dst) {
2049 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002050 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002051 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002052 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002053}
2054
Brian Carlstromea46f952013-07-30 01:26:50 -07002055mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002056 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002057 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002058 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002059 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002060 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002061
Brian Carlstromea46f952013-07-30 01:26:50 -07002062 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002063 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002064 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002065 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002066 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002067 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002068
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002069 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002070 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002071 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002072 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002073
Ian Rogers19846512012-02-24 11:42:47 -08002074 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002075 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002076
Andreas Gampe51829322014-08-25 15:05:04 -07002077 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002078
Ian Rogersdfb325e2013-10-30 01:00:44 -07002079 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002080 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002081 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2082 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002083 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002084 klass->SetFinalizable();
2085 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002086 std::string temp;
2087 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002088 // The Enum class declares a "final" finalize() method to prevent subclasses from
2089 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2090 // subclasses, so we exclude it here.
2091 // We also want to avoid setting the flag on Object, where we know that finalize() is
2092 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002093 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2094 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002095 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002096 }
2097 }
2098 }
2099 } else if (method_name[0] == '<') {
2100 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002101 bool is_init = (strcmp("<init>", method_name) == 0);
2102 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002103 if (UNLIKELY(!is_init && !is_clinit)) {
2104 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2105 } else {
2106 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2107 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002108 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002109 access_flags |= kAccConstructor;
2110 }
2111 }
2112 }
2113 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002114
Mathieu Chartier66f19252012-09-18 08:57:04 -07002115 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002116}
2117
Ian Rogers7b078e82014-09-10 14:44:24 -07002118void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002119 StackHandleScope<1> hs(self);
2120 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002121 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2122 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002123 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002124}
2125
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002126void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002127 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002128 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002129 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002130 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002131}
2132
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002133bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002134 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002135 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002136 mirror::DexCache* dex_cache = GetDexCache(i);
2137 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002138 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002139 }
2140 }
2141 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002142}
2143
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002144bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002145 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002146 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002147}
2148
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002149void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002150 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002151 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002152 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002153 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2154 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002155 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002156 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002157 if (log_new_dex_caches_roots_) {
2158 // TODO: This is not safe if we can remove dex caches.
2159 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2160 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002161}
2162
Brian Carlstromaded5f72011-10-07 17:15:04 -07002163void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002164 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002165 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002166 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002167 if (IsDexFileRegisteredLocked(dex_file)) {
2168 return;
2169 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002170 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002171 // Don't alloc while holding the lock, since allocation may need to
2172 // suspend all threads and another thread may need the dex_lock_ to
2173 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002174 StackHandleScope<1> hs(self);
2175 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002176 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2177 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002178 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002179 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002180 if (IsDexFileRegisteredLocked(dex_file)) {
2181 return;
2182 }
2183 RegisterDexFileLocked(dex_file, dex_cache);
2184 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002185}
2186
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002187void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002188 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002189 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002190 RegisterDexFileLocked(dex_file, dex_cache);
2191}
2192
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002193mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002194 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002195 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002196 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002197 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002198 if (dex_cache->GetDexFile() == &dex_file) {
2199 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002200 }
2201 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002202 // Search matching by location name.
2203 std::string location(dex_file.GetLocation());
2204 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002205 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002206 if (dex_cache->GetDexFile()->GetLocation() == location) {
2207 return dex_cache;
2208 }
2209 }
2210 // Failure, dump diagnostic and abort.
2211 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002212 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002213 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2214 }
2215 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002216 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002217}
2218
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002219void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002220 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002221 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002222 mirror::DexCache* dex_cache = GetDexCache(i);
2223 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002224 }
2225}
2226
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002227mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002228 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002229 if (UNLIKELY(klass == nullptr)) {
2230 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002231 }
2232 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002233}
2234
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002235mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2236 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002237 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002238 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002239 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002240 StackHandleScope<1> hs(self);
2241 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002242 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002243 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2244 h_class->SetPrimitiveType(type);
2245 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002246 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002247 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002248 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002249 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002250 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07002251}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002252
Brian Carlstrombe977852011-07-19 14:54:54 -07002253// Create an array class (i.e. the class object for the array, not the
2254// array itself). "descriptor" looks like "[C" or "[[[[B" or
2255// "[Ljava/lang/String;".
2256//
2257// If "descriptor" refers to an array of primitives, look up the
2258// primitive type's internally-generated class object.
2259//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002260// "class_loader" is the class loader of the class that's referring to
2261// us. It's used to ensure that we're looking for the element type in
2262// the right context. It does NOT become the class loader for the
2263// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002264//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002265// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002266mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002267 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002268 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002269 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002270 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002271 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2272 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002273 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002274 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002275 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002276 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2277 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002278 if (component_type.Get() == nullptr) {
2279 DCHECK(self->IsExceptionPending());
2280 return nullptr;
2281 } else {
2282 self->ClearException();
2283 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002284 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002285 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2286 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2287 return nullptr;
2288 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002289 // See if the component type is already loaded. Array classes are
2290 // always associated with the class loader of their underlying
2291 // element type -- an array of Strings goes with the loader for
2292 // java/lang/String -- so we need to look for it there. (The
2293 // caller should have checked for the existence of the class
2294 // before calling here, but they did so with *their* class loader,
2295 // not the component type's loader.)
2296 //
2297 // If we find it, the caller adds "loader" to the class' initiating
2298 // loader list, which should prevent us from going through this again.
2299 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002300 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002301 // are the same, because our caller (FindClass) just did the
2302 // lookup. (Even if we get this wrong we still have correct behavior,
2303 // because we effectively do this lookup again when we add the new
2304 // class to the hash table --- necessary because of possible races with
2305 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002306 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002307 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002308 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002309 return new_class;
2310 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002311 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002312
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002313 // Fill out the fields in the Class.
2314 //
2315 // It is possible to execute some methods against arrays, because
2316 // all arrays are subclasses of java_lang_Object_, so we need to set
2317 // up a vtable. We can just point at the one in java_lang_Object_.
2318 //
2319 // Array classes are simple enough that we don't need to do a full
2320 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002321 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002322 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002323 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002324 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002325 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002326 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002327 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002328 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002329 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002330 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002331 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002332 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002333 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002334 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002335 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002336 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002337 } else if (strcmp(descriptor, "[J") == 0) {
2338 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002339 }
2340 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002341 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002342 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002343 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002344 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002345 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002346 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002347 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002348 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002349 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002350 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002351 new_class->SetSuperClass(java_lang_Object);
2352 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002353 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002354 new_class->SetClassLoader(component_type->GetClassLoader());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002355 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002356 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002357 StackHandleScope<mirror::Class::kImtSize> hs2(self,
2358 Runtime::Current()->GetImtUnimplementedMethod());
2359 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002360 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002361 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002362 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002363 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002364
2365
2366 // All arrays have java/lang/Cloneable and java/io/Serializable as
2367 // interfaces. We need to set that up here, so that stuff like
2368 // "instanceof" works right.
2369 //
2370 // Note: The GC could run during the call to FindSystemClass,
2371 // so we need to make sure the class object is GC-valid while we're in
2372 // there. Do this by clearing the interface list so the GC will just
2373 // think that the entries are null.
2374
2375
2376 // Use the single, global copies of "interfaces" and "iftable"
2377 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002378 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002379 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002380 CHECK(array_iftable != nullptr);
2381 new_class->SetIfTable(array_iftable);
2382 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002383
Elliott Hughes00626c22013-06-14 15:04:14 -07002384 // Inherit access flags from the component type.
2385 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2386 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2387 access_flags &= kAccJavaFlagsMask;
2388 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002389 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002390 access_flags |= kAccAbstract | kAccFinal;
2391 access_flags &= ~kAccInterface;
2392
2393 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002394
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002395 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002396 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002397 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002398 }
2399 // Another thread must have loaded the class after we
2400 // started but before we finished. Abandon what we've
2401 // done.
2402 //
2403 // (Yes, this happens.)
2404
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002405 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002406}
2407
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002408mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002409 switch (type) {
2410 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002411 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002412 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002413 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002414 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002415 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002416 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002417 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002418 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002419 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002420 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002421 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002422 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002423 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002424 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002425 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002426 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002427 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002428 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002429 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002430 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002431 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002432 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002433 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002434}
2435
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002436mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2437 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002438 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002439 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002440 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002441 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002442 source += " from ";
2443 source += dex_cache->GetLocation()->ToModifiedUtf8();
2444 }
2445 LOG(INFO) << "Loaded class " << descriptor << source;
2446 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002447 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002448 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002449 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002450 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002451 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002452 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002453 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002454 // Check a class loaded with the system class loader matches one in the image if the class
2455 // is in the image.
2456 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002457 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002458 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002459 }
2460 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002461 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002462 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002463 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002464 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002465 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002466 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002467}
2468
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002469mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2470 size_t hash) {
2471 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002472 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
2473 hash);
2474 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002475 CHECK(klass->IsProxyClass());
2476 return nullptr;
2477 }
2478
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002479 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002480 CHECK_NE(existing, klass) << descriptor;
2481 CHECK(!existing->IsResolved()) << descriptor;
2482 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2483
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002484 CHECK(!klass->IsTemp()) << descriptor;
2485 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2486 dex_cache_image_class_lookup_required_) {
2487 // Check a class loaded with the system class loader matches one in the image if the class
2488 // is in the image.
2489 existing = LookupClassFromImage(descriptor);
2490 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002491 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002492 }
2493 }
2494 VerifyObject(klass);
2495
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002496 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002497 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002498 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002499 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002500 }
2501
2502 return existing;
2503}
2504
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002505bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002506 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002507 auto pair = std::make_pair(descriptor, class_loader);
2508 auto it = class_table_.Find(pair);
2509 if (it != class_table_.end()) {
2510 class_table_.Erase(it);
2511 return true;
2512 }
2513 it = pre_zygote_class_table_.Find(pair);
2514 if (it != pre_zygote_class_table_.end()) {
2515 pre_zygote_class_table_.Erase(it);
2516 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08002517 }
2518 return false;
2519}
2520
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002521mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002522 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002523 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002524 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002525 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002526 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002527 return result;
2528 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002529 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002530 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2531 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002532 } else {
2533 // Lookup failed but need to search dex_caches_.
2534 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002535 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002536 InsertClass(descriptor, result, hash);
2537 } else {
2538 // Searching the image dex files/caches failed, we don't want to get into this situation
2539 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2540 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07002541 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002542 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2543 MoveImageClassesToClassTable();
2544 }
2545 }
2546 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002547 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002548}
2549
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002550mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002551 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002552 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002553 auto descriptor_pair = std::make_pair(descriptor, class_loader);
2554 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
2555 if (it == pre_zygote_class_table_.end()) {
2556 it = class_table_.FindWithHash(descriptor_pair, hash);
2557 if (it == class_table_.end()) {
2558 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07002559 }
2560 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002561 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002562}
2563
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002564static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2565 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2566 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002567 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002568 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2569 return root->AsObjectArray<mirror::DexCache>();
2570}
2571
2572void ClassLinker::MoveImageClassesToClassTable() {
2573 Thread* self = Thread::Current();
2574 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2575 if (!dex_cache_image_class_lookup_required_) {
2576 return; // All dex cache classes are already in the class table.
2577 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002578 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002579 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002580 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002581 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2582 mirror::DexCache* dex_cache = dex_caches->Get(i);
2583 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2584 for (int32_t j = 0; j < types->GetLength(); j++) {
2585 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002586 if (klass != nullptr) {
2587 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002588 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002589 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002590 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
2591 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002592 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002593 << PrettyClassAndClassLoader(klass);
2594 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002595 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002596 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002597 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002598 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002599 }
2600 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002601 }
2602 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002603 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002604}
2605
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002606void ClassLinker::MoveClassTableToPreZygote() {
2607 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2608 DCHECK(pre_zygote_class_table_.Empty());
2609 pre_zygote_class_table_ = std::move(class_table_);
2610 class_table_.Clear();
2611}
2612
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002613mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002614 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002615 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2616 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2617 mirror::DexCache* dex_cache = dex_caches->Get(i);
2618 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00002619 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002620 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002621 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002622 const DexFile::TypeId* type_id =
2623 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002624 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002625 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2626 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002627 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002628 return klass;
2629 }
2630 }
2631 }
2632 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002633 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002634}
2635
2636void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
2637 result.clear();
2638 if (dex_cache_image_class_lookup_required_) {
2639 MoveImageClassesToClassTable();
2640 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002641 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2642 while (true) {
2643 auto it = class_table_.Find(descriptor);
2644 if (it == class_table_.end()) {
2645 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002646 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002647 result.push_back(it->Read());
2648 class_table_.Erase(it);
2649 }
2650 for (mirror::Class* k : result) {
2651 class_table_.Insert(GcRoot<mirror::Class>(k));
2652 }
2653 size_t pre_zygote_start = result.size();
2654 // Now handle the pre zygote table.
2655 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
2656 // called from the debugger.
2657 while (true) {
2658 auto it = pre_zygote_class_table_.Find(descriptor);
2659 if (it == pre_zygote_class_table_.end()) {
2660 break;
2661 }
2662 result.push_back(it->Read());
2663 pre_zygote_class_table_.Erase(it);
2664 }
2665 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
2666 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002667 }
2668}
2669
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002670void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002671 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002672 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002673
Ian Rogers9ffb0392012-09-10 11:56:50 -07002674 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002675 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002676 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002677 return;
2678 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002679 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002680 return;
2681 }
jeffhao98eacac2011-09-14 16:11:53 -07002682
Ian Rogers9ffb0392012-09-10 11:56:50 -07002683 // The class might already be erroneous, for example at compile time if we attempted to verify
2684 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002685 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002686 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002687 return;
2688 }
2689
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002690 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002691 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002692 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002693 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002694 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002695 CHECK(!Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002696 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002697 }
jeffhao98eacac2011-09-14 16:11:53 -07002698
Jeff Hao4a200f52014-04-01 14:58:49 -07002699 // Skip verification if disabled.
2700 if (!Runtime::Current()->IsVerificationEnabled()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002701 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002702 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002703 return;
2704 }
2705
Ian Rogers9ffb0392012-09-10 11:56:50 -07002706 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002707 StackHandleScope<2> hs(self);
2708 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002709 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002710 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002711 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002712
2713 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002714 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002715 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002716 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002717 std::string error_msg(
2718 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2719 PrettyDescriptor(klass.Get()).c_str(),
2720 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002721 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002722 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002723 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002724 self->ClearException();
2725 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002726 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2727 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002728 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002729 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002730 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002731 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002732 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2733 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002734 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002735 return;
2736 }
2737 }
2738
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002739 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002740 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002741 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002742 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002743 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002744 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002745 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002746 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002747 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2748 PrettyDescriptor(klass.Get()).c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002749 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002750 return;
2751 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002752 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002753 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002754 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002755 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002756 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002757 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002758 }
2759 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002760 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002761 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002762 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2763 << " because: " << error_msg;
2764 }
Ian Rogers1f539342012-10-03 21:09:42 -07002765 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002766 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002767 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002768 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002769 // Even though there were no verifier failures we need to respect whether the super-class
2770 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002771 if (super.Get() == nullptr || super->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002772 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002773 } else {
2774 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002775 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002776 // Pretend a soft failure occured so that we don't consider the class verified below.
2777 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002778 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002779 } else {
2780 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2781 // Soft failures at compile time should be retried at runtime. Soft
2782 // failures at runtime will be handled by slow paths in the generated
2783 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002784 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002785 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002786 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002787 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002788 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2789 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07002790 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002791 }
2792 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002793 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002794 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08002795 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2796 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002797 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002798 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002799 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002800 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002801 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002802 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002803 // Let the interpreter know it by setting the kAccPreverified flag onto each
2804 // method.
2805 // Note: we're going here during compilation and at runtime. When we set the
2806 // kAccPreverified flag when compiling image classes, the flag is recorded
2807 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07002808 EnsurePreverifiedMethods(klass);
2809 }
2810}
2811
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002812void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002813 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002814 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07002815 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002816 }
jeffhao98eacac2011-09-14 16:11:53 -07002817}
2818
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002819bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
2820 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002821 // If we're compiling, we can only verify the class using the oat file if
2822 // we are not compiling the image or if the class we're verifying is not part of
2823 // the app. In other words, we will only check for preverification of bootclasspath
2824 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002825 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002826 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002827 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002828 return false;
2829 }
2830 // We are compiling an app (not the image).
2831
2832 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002833 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002834 return false;
2835 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002836 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002837
Richard Uhler07b3c232015-03-31 15:57:54 -07002838 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002839 // In case we run without an image there won't be a backing oat file.
2840 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07002841 return false;
2842 }
2843
Andreas Gampe76bd8802014-12-10 16:43:58 -08002844 // We may be running with a preopted oat file but without image. In this case,
2845 // we don't skip verification of preverified classes to ensure we initialize
2846 // dex caches with all types resolved during verification.
2847 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
2848 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
2849 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
2850 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002851 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08002852 !Runtime::Current()->GetHeap()->HasImageSpace() &&
2853 klass->GetClassLoader() != nullptr) {
2854 return false;
2855 }
2856
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002857 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002858 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002859 if (oat_file_class_status == mirror::Class::kStatusVerified ||
2860 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002861 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002862 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002863 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002864 // Compile time verification failed with a soft error. Compile time verification can fail
2865 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002866 // class ... {
2867 // Foo x;
2868 // .... () {
2869 // if (...) {
2870 // v1 gets assigned a type of resolved class Foo
2871 // } else {
2872 // v1 gets assigned a type of unresolved class Bar
2873 // }
2874 // iput x = v1
2875 // } }
2876 // when we merge v1 following the if-the-else it results in Conflict
2877 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2878 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2879 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2880 // at compile time).
2881 return false;
2882 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002883 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07002884 // Compile time verification failed with a hard error. This is caused by invalid instructions
2885 // in the class. These errors are unrecoverable.
2886 return false;
2887 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002888 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002889 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2890 // not loading the class.
2891 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2892 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002893 return false;
2894 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002895 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002896 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002897 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07002898 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08002899 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002900}
2901
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002902void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002903 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002904 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2905 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2906 }
2907 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2908 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2909 }
2910}
2911
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002912void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07002913 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002914 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2915 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002916 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002917 return; // native or abstract method
2918 }
2919 if (code_item->tries_size_ == 0) {
2920 return; // nothing to process
2921 }
Ian Rogers13735952014-10-08 12:43:28 -07002922 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002923 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2924 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2925 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2926 CatchHandlerIterator iterator(handlers_ptr);
2927 for (; iterator.HasNext(); iterator.Next()) {
2928 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2929 // unresolved exception types will be ignored by exception delivery
2930 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002931 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002932 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002933 DCHECK(Thread::Current()->IsExceptionPending());
2934 Thread::Current()->ClearException();
2935 }
2936 }
2937 }
2938 handlers_ptr = iterator.EndDataPointer();
2939 }
2940}
2941
Brian Carlstromea46f952013-07-30 01:26:50 -07002942static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002943static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
2944 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08002945
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002946mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07002947 jobjectArray interfaces, jobject loader,
2948 jobjectArray methods, jobjectArray throws) {
2949 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002950 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002951 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002952 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002953 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002954 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002955 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002956 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002957 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002958 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07002959 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
2960 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002961 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08002962 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002963 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002964 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002965 klass->SetDexCache(proxy_class->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002966 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08002967
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002968 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002969 const size_t num_fields = 2;
2970 ArtField* sfields = AllocArtFieldArray(self, num_fields);
2971 klass->SetSFields(sfields);
2972 klass->SetNumStaticFields(num_fields);
2973
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002974 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2975 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002976 ArtField* interfaces_sfield = &sfields[0];
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002977 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002978 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002979 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002980
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002981 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002982 ArtField* throws_sfield = &sfields[1];
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002983 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002984 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002985 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002986
Ian Rogers466bb252011-10-14 03:29:56 -07002987 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07002988 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002989 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002990 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002991 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002992 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002993 }
2994 klass->SetDirectMethods(directs);
2995 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002996 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002997 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002998 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002999 }
3000 klass->SetDirectMethod(0, constructor);
3001 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003002
Mathieu Chartier590fee92013-09-13 13:46:47 -07003003 // Create virtual method using specified prototypes.
3004 size_t num_virtual_methods =
3005 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003006 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003007 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3008 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003009 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003010 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003011 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003012 }
3013 klass->SetVirtualMethods(virtuals);
3014 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003015 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003016 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003017 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3018 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003019 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003020 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003021 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003022 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003023 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003024 }
3025 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003026 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003027
3028 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003029 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003030 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003031
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003032 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3033 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003034 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003035 // Must hold lock on object when resolved.
3036 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003037 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003038 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003039 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003040 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003041 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003042 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003043 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003044 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003045
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003046 CHECK(klass->IsRetired());
3047 CHECK_NE(klass.Get(), new_class);
3048 klass.Assign(new_class);
3049
3050 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003051 interfaces_sfield->SetObject<false>(klass.Get(),
3052 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003053 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003054 throws_sfield->SetObject<false>(klass.Get(),
3055 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003056
3057 {
3058 // Lock on klass is released. Lock new class object.
3059 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003060 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003061 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003062
3063 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003064 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003065 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003066 CheckProxyConstructor(klass->GetDirectMethod(0));
3067 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003068 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003069 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3070 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003071 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3072 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003073 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003074 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003075
Mathieu Chartier590fee92013-09-13 13:46:47 -07003076 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003077 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003078 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003079 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3080
3081 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003082 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003083 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003084
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003085 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003086 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003087 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003088 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003089 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003090 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3091 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003092 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003093 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003094}
3095
Ian Rogersef7d42f2014-01-06 12:55:46 -08003096std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003097 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003098 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003099 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003100 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3101}
3102
Ian Rogersef7d42f2014-01-06 12:55:46 -08003103mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3104 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003105 DCHECK(proxy_class->IsProxyClass());
3106 DCHECK(proxy_method->IsProxyMethod());
3107 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003108 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003109 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003110 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003111 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003112 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003113 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003114 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003115 break;
3116 }
3117 }
3118 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003119 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003120 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003121 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003122 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003123 return resolved_method;
3124}
3125
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003126
Brian Carlstromea46f952013-07-30 01:26:50 -07003127mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003128 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003129 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003130 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003131 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003132 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003133 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3134 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003135 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3136 // constructor method.
3137 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3138 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003139 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3140 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003141 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3142 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003143 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003144 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003145 }
Ian Rogers466bb252011-10-14 03:29:56 -07003146 // Make this constructor public and fix the class to be our Proxy version
3147 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003148 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003149 return constructor;
3150}
3151
Brian Carlstromea46f952013-07-30 01:26:50 -07003152static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003153 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003154 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003155 CHECK_STREQ(constructor->GetName(), "<init>");
3156 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3157 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003158 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003159}
3160
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003161mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003162 Handle<mirror::Class> klass,
3163 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003164 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3165 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003166 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003167 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003168 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003169 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003170 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003171 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003172 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003173 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003174 }
Ian Rogers466bb252011-10-14 03:29:56 -07003175
3176 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3177 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003178 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003179 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003180
Ian Rogers466bb252011-10-14 03:29:56 -07003181 // At runtime the method looks like a reference and argument saving method, clone the code
3182 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003183 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003184 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003185
Ian Rogersc2b44472011-12-14 21:17:17 -08003186 return method;
3187}
Jesse Wilson95caa792011-10-12 18:14:17 -04003188
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003189static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3190 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003191 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003192 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003193 CHECK(!prototype->IsFinal());
3194 CHECK(method->IsFinal());
3195 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003196
3197 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3198 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07003199 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3200 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08003201 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3202
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003203 CHECK_STREQ(method->GetName(), prototype->GetName());
3204 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003205 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07003206 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003207}
3208
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003209static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3210 bool can_init_parents)
3211 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003212 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003213 return true;
3214 }
3215 if (!can_init_statics) {
3216 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003217 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003218 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003219 return false;
3220 }
3221 // Check if there are encoded static values needing initialization.
3222 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003223 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003224 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003225 if (dex_class_def->static_values_off_ != 0) {
3226 return false;
3227 }
3228 }
3229 }
3230 if (!klass->IsInterface() && klass->HasSuperClass()) {
3231 mirror::Class* super_class = klass->GetSuperClass();
3232 if (!can_init_parents && !super_class->IsInitialized()) {
3233 return false;
3234 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003235 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003236 return false;
3237 }
3238 }
3239 }
3240 return true;
3241}
3242
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003243bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07003244 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003245 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3246
3247 // Are we already initialized and therefore done?
3248 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3249 // an initialized class will never change its state.
3250 if (klass->IsInitialized()) {
3251 return true;
3252 }
3253
3254 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003255 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003256 return false;
3257 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003258
Ian Rogers7b078e82014-09-10 14:44:24 -07003259 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003260 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003261 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003262 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003263
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003264 // Re-check under the lock in case another thread initialized ahead of us.
3265 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003266 return true;
3267 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003268
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003269 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003270 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003271 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003272 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003273 return false;
3274 }
3275
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003276 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003277
3278 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003279 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003280 if (!klass->IsVerified()) {
3281 // We failed to verify, expect either the klass to be erroneous or verification failed at
3282 // compile time.
3283 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003284 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003285 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003286 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003287 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003288 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003289 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003290 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003291 } else {
3292 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003293 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003294 }
3295
Brian Carlstromd1422f82011-09-28 11:37:09 -07003296 // If the class is kStatusInitializing, either this thread is
3297 // initializing higher up the stack or another thread has beat us
3298 // to initializing and we need to wait. Either way, this
3299 // invocation of InitializeClass will not be responsible for
3300 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003301 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003302 // Could have got an exception during verification.
3303 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003304 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003305 return false;
3306 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003307 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003308 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003309 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003310 return true;
3311 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003312 // No. That's fine. Wait for another thread to finish initializing.
3313 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003314 }
3315
3316 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003317 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003318 return false;
3319 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003320 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003321
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003322 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003323
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003324 // From here out other threads may observe that we're initializing and so changes of state
3325 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003326 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003327 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003328
3329 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003330 }
3331
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003332 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003333 if (!klass->IsInterface() && klass->HasSuperClass()) {
3334 mirror::Class* super_class = klass->GetSuperClass();
3335 if (!super_class->IsInitialized()) {
3336 CHECK(!super_class->IsInterface());
3337 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003338 StackHandleScope<1> hs(self);
3339 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003340 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003341 if (!super_initialized) {
3342 // The super class was verified ahead of entering initializing, we should only be here if
3343 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003344 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003345 << "Super class initialization failed for "
3346 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003347 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003348 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003349 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003350 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003351 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003352 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003353 return false;
3354 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003355 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003356 }
3357
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003358 const size_t num_static_fields = klass->NumStaticFields();
3359 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003360 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003361 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003362 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003363 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003364 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003365 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003366
3367 // Eagerly fill in static fields so that the we don't have to do as many expensive
3368 // Class::FindStaticField in ResolveField.
3369 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003370 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003371 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003372 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003373 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003374 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003375 } else {
3376 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003377 }
3378 }
3379
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003380 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3381 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003382 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003383 ClassDataItemIterator field_it(dex_file, class_data);
3384 if (value_it.HasNext()) {
3385 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003386 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003387 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003388 ArtField* field = ResolveField(
3389 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003390 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003391 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003392 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003393 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003394 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003395 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003396 }
3397 }
3398 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003399
Ian Rogersd91d6d62013-09-25 20:26:14 -07003400 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003401 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003402 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003403 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003404 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003405 }
3406
Ian Rogers7b078e82014-09-10 14:44:24 -07003407 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003408 uint64_t t1 = NanoTime();
3409
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003410 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003411 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003412 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003413
3414 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003415 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003416 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003417 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003418 } else if (Runtime::Current()->IsTransactionAborted()) {
3419 // The exception thrown when the transaction aborted has been caught and cleared
3420 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003421 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3422 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02003423 Runtime::Current()->ThrowTransactionAbortError(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003424 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003425 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003426 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003427 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3428 RuntimeStats* thread_stats = self->GetStats();
3429 ++global_stats->class_init_count;
3430 ++thread_stats->class_init_count;
3431 global_stats->class_init_time_ns += (t1 - t0);
3432 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003433 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003434 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003435 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003436 std::string temp;
3437 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003438 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003439 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003440 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003441 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003442 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003443 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003444 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003445}
3446
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003447bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003448 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003449 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003450 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003451 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003452 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003453 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003454
3455 // When we wake up, repeat the test for init-in-progress. If
3456 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003457 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003458 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003459 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003460 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003461 return false;
3462 }
3463 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003464 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003465 continue;
3466 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003467 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3468 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003469 // Compile time initialization failed.
3470 return false;
3471 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003472 if (klass->IsErroneous()) {
3473 // The caller wants an exception, but it was thrown in a
3474 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003475 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003476 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003477 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003478 return false;
3479 }
3480 if (klass->IsInitialized()) {
3481 return true;
3482 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003483 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003484 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003485 }
Ian Rogers07140832014-09-30 15:43:59 -07003486 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003487}
3488
Ian Rogersb5fb2072014-12-02 17:22:02 -08003489static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
3490 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003491 Handle<mirror::ArtMethod> method2,
3492 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08003493 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3494 {
3495 StackHandleScope<1> hs(self);
3496 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00003497 mirror::Class* other_return_type = method2->GetReturnType();
3498 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
3499 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003500 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3501 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3502 return_type.Get(),
3503 PrettyClassAndClassLoader(other_return_type).c_str(),
3504 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003505 return false;
3506 }
3507 }
3508 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3509 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3510 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003511 if (types2 != nullptr && types2->Size() != 0) {
3512 *error_msg = StringPrintf("Type list mismatch with %s",
3513 PrettyMethod(method2.Get(), true).c_str());
3514 return false;
3515 }
3516 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003517 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003518 if (types1->Size() != 0) {
3519 *error_msg = StringPrintf("Type list mismatch with %s",
3520 PrettyMethod(method2.Get(), true).c_str());
3521 return false;
3522 }
3523 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003524 }
3525 uint32_t num_types = types1->Size();
3526 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003527 *error_msg = StringPrintf("Type list mismatch with %s",
3528 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08003529 return false;
3530 }
3531 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003532 StackHandleScope<1> hs(self);
3533 Handle<mirror::Class> param_type(hs.NewHandle(
3534 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003535 mirror::Class* other_param_type =
3536 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00003537 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
3538 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003539 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3540 i,
3541 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3542 param_type.Get(),
3543 PrettyClassAndClassLoader(other_param_type).c_str(),
3544 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003545 return false;
3546 }
3547 }
3548 return true;
3549}
3550
3551
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003552bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003553 if (klass->IsInterface()) {
3554 return true;
3555 }
Ian Rogers151f2212014-05-06 11:27:27 -07003556 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003557 Thread* self = Thread::Current();
3558 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003559 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
3560 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003561 if (klass->HasSuperClass() &&
3562 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003563 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003564 h_m.Assign(klass->GetVTableEntry(i));
3565 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003566 if (h_m.Get() != super_h_m.Get()) {
3567 std::string error_msg;
3568 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3569 ThrowLinkageError(klass.Get(),
3570 "Class %s method %s resolves differently in superclass %s: %s",
3571 PrettyDescriptor(klass.Get()).c_str(),
3572 PrettyMethod(h_m.Get()).c_str(),
3573 PrettyDescriptor(klass->GetSuperClass()).c_str(),
3574 error_msg.c_str());
3575 return false;
3576 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003577 }
3578 }
3579 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003580 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003581 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3582 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3583 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003584 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3585 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003586 if (h_m.Get() != super_h_m.Get()) {
3587 std::string error_msg;
3588 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3589 ThrowLinkageError(klass.Get(),
3590 "Class %s method %s resolves differently in interface %s: %s",
3591 PrettyDescriptor(klass.Get()).c_str(),
3592 PrettyMethod(h_m.Get()).c_str(),
3593 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
3594 error_msg.c_str());
3595 return false;
3596 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003597 }
3598 }
3599 }
3600 }
3601 return true;
3602}
3603
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003604bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
3605 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003606 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003607 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003608 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003609 return true;
3610 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003611 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003612 if (!success) {
3613 if (can_init_fields && can_init_parents) {
3614 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3615 }
3616 } else {
3617 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003618 }
3619 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003620}
3621
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003622void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003623 ArtField* fields = new_class->GetIFields();
3624 for (size_t i = 0, count = new_class->NumInstanceFields(); i < count; i++) {
3625 if (fields[i].GetDeclaringClass() == temp_class) {
3626 fields[i].SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003627 }
3628 }
3629
3630 fields = new_class->GetSFields();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003631 for (size_t i = 0, count = new_class->NumStaticFields(); i < count; i++) {
3632 if (fields[i].GetDeclaringClass() == temp_class) {
3633 fields[i].SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003634 }
3635 }
3636
3637 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3638 if (methods != nullptr) {
3639 for (int index = 0; index < methods->GetLength(); index ++) {
3640 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3641 methods->Get(index)->SetDeclaringClass(new_class);
3642 }
3643 }
3644 }
3645
3646 methods = new_class->GetVirtualMethods();
3647 if (methods != nullptr) {
3648 for (int index = 0; index < methods->GetLength(); index ++) {
3649 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3650 methods->Get(index)->SetDeclaringClass(new_class);
3651 }
3652 }
3653 }
3654}
3655
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003656bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3657 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003658 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003659 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003660
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003661 if (!LinkSuperClass(klass)) {
3662 return false;
3663 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003664 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
3665 self, Runtime::Current()->GetImtUnimplementedMethod());
3666 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003667 return false;
3668 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003669 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003670 return false;
3671 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003672 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07003673 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003674 return false;
3675 }
3676 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003677 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003678
3679 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3680 // We don't need to retire this class as it has no embedded tables or it was created the
3681 // correct size during class linker initialization.
3682 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3683
3684 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003685 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003686 }
3687
3688 // This will notify waiters on klass that saw the not yet resolved
3689 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003690 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003691 *new_class = klass.Get();
3692 } else {
3693 CHECK(!klass->IsResolved());
3694 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003695 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003696 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003697 CHECK(self->IsExceptionPending()); // Expect an OOME.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003698 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003699 return false;
3700 }
3701
3702 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3703 StackHandleScope<1> hs(self);
3704 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3705 ObjectLock<mirror::Class> lock(self, new_class_h);
3706
3707 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
3708
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003709 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
3710 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003711 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003712
3713 // This will notify waiters on temp class that saw the not yet resolved class in the
3714 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003715 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003716
3717 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
3718 // This will notify waiters on new_class that saw the not yet resolved
3719 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003720 mirror::Class::SetStatus(new_class_h, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003721 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003722 return true;
3723}
3724
Andreas Gampefd9eb392014-11-06 16:52:58 -08003725static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
3726 size_t* virtual_methods,
3727 size_t* direct_methods,
3728 size_t* static_fields,
3729 size_t* instance_fields) {
3730 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
3731
3732 while (dex_data.HasNextStaticField()) {
3733 dex_data.Next();
3734 (*static_fields)++;
3735 }
3736 while (dex_data.HasNextInstanceField()) {
3737 dex_data.Next();
3738 (*instance_fields)++;
3739 }
3740 while (dex_data.HasNextDirectMethod()) {
3741 (*direct_methods)++;
3742 dex_data.Next();
3743 }
3744 while (dex_data.HasNextVirtualMethod()) {
3745 (*virtual_methods)++;
3746 dex_data.Next();
3747 }
3748 DCHECK(!dex_data.HasNext());
3749}
3750
3751static void DumpClass(std::ostream& os,
3752 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
3753 const char* suffix) {
3754 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
3755 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
3756 os << " Static fields:\n";
3757 while (dex_data.HasNextStaticField()) {
3758 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3759 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3760 dex_data.Next();
3761 }
3762 os << " Instance fields:\n";
3763 while (dex_data.HasNextInstanceField()) {
3764 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3765 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3766 dex_data.Next();
3767 }
3768 os << " Direct methods:\n";
3769 while (dex_data.HasNextDirectMethod()) {
3770 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3771 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3772 dex_data.Next();
3773 }
3774 os << " Virtual methods:\n";
3775 while (dex_data.HasNextVirtualMethod()) {
3776 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3777 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3778 dex_data.Next();
3779 }
3780}
3781
3782static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3783 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
3784 std::ostringstream os;
3785 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
3786 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
3787 return os.str();
3788}
3789
3790
3791// Very simple structural check on whether the classes match. Only compares the number of
3792// methods and fields.
3793static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3794 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
3795 std::string* error_msg) {
3796 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
3797 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
3798
3799 // Counters for current dex file.
3800 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
3801 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
3802 &dex_instance_fields1);
3803 // Counters for compile-time dex file.
3804 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
3805 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
3806 &dex_instance_fields2);
3807
3808 if (dex_virtual_methods1 != dex_virtual_methods2) {
3809 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3810 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
3811 dex_virtual_methods2, class_dump.c_str());
3812 return false;
3813 }
3814 if (dex_direct_methods1 != dex_direct_methods2) {
3815 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3816 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
3817 dex_direct_methods2, class_dump.c_str());
3818 return false;
3819 }
3820 if (dex_static_fields1 != dex_static_fields2) {
3821 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3822 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
3823 dex_static_fields2, class_dump.c_str());
3824 return false;
3825 }
3826 if (dex_instance_fields1 != dex_instance_fields2) {
3827 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3828 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
3829 dex_instance_fields2, class_dump.c_str());
3830 return false;
3831 }
3832
3833 return true;
3834}
3835
3836// Checks whether a the super-class changed from what we had at compile-time. This would
3837// invalidate quickening.
3838static bool CheckSuperClassChange(Handle<mirror::Class> klass,
3839 const DexFile& dex_file,
3840 const DexFile::ClassDef& class_def,
3841 mirror::Class* super_class)
3842 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3843 // Check for unexpected changes in the superclass.
3844 // Quick check 1) is the super_class class-loader the boot class loader? This always has
3845 // precedence.
3846 if (super_class->GetClassLoader() != nullptr &&
3847 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
3848 // which is implied by different dex cache.
3849 klass->GetDexCache() != super_class->GetDexCache()) {
3850 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
3851 // definition for the super-class, and (b) the files are in separate oat files. The oat files
3852 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07003853 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
3854 const OatFile* class_oat_file = nullptr;
3855 if (class_oat_dex_file != nullptr) {
3856 class_oat_file = class_oat_dex_file->GetOatFile();
3857 }
3858
Andreas Gampefd9eb392014-11-06 16:52:58 -08003859 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07003860 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
3861 const OatFile* loaded_super_oat_file = nullptr;
3862 if (loaded_super_oat_dex_file != nullptr) {
3863 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
3864 }
3865
Andreas Gampefd9eb392014-11-06 16:52:58 -08003866 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
3867 // Now check (a).
3868 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
3869 if (super_class_def != nullptr) {
3870 // Uh-oh, we found something. Do our check.
3871 std::string error_msg;
3872 if (!SimpleStructuralCheck(dex_file, *super_class_def,
3873 super_class->GetDexFile(), *super_class->GetClassDef(),
3874 &error_msg)) {
3875 // Print a warning to the log. This exception might be caught, e.g., as common in test
3876 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
3877 // only save the type of the exception.
3878 LOG(WARNING) << "Incompatible structural change detected: " <<
3879 StringPrintf(
3880 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3881 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3882 class_oat_file->GetLocation().c_str(),
3883 loaded_super_oat_file->GetLocation().c_str(),
3884 error_msg.c_str());
3885 ThrowIncompatibleClassChangeError(klass.Get(),
3886 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3887 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3888 class_oat_file->GetLocation().c_str(),
3889 loaded_super_oat_file->GetLocation().c_str(),
3890 error_msg.c_str());
3891 return false;
3892 }
3893 }
3894 }
3895 }
3896 }
3897 return true;
3898}
3899
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003900bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003901 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003902 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3903 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003904 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003905 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003906 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003907 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003908 return false;
3909 }
Ian Rogersbe125a92012-01-11 15:19:49 -08003910 // Verify
3911 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003912 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003913 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003914 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08003915 return false;
3916 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003917 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003918 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08003919
3920 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
3921 DCHECK(Thread::Current()->IsExceptionPending());
3922 return false;
3923 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003924 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003925 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003926 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003927 for (size_t i = 0; i < interfaces->Size(); i++) {
3928 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003929 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003930 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003931 DCHECK(Thread::Current()->IsExceptionPending());
3932 return false;
3933 }
3934 // Verify
3935 if (!klass->CanAccess(interface)) {
3936 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003937 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003938 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003939 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003940 return false;
3941 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003942 }
3943 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003944 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003945 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003946 return true;
3947}
3948
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003949bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003950 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003951 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003952 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003953 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003954 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003955 return false;
3956 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003957 return true;
3958 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003959 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003960 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
3961 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003962 return false;
3963 }
3964 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003965 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003966 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003967 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003968 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003969 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003970 return false;
3971 }
3972 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003973 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003974 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003975 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003976 return false;
3977 }
Elliott Hughes20cde902011-10-04 17:37:27 -07003978
Brian Carlstromf3632832014-05-20 15:36:53 -07003979 // Inherit kAccClassIsFinalizable from the superclass in case this
3980 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07003981 if (super->IsFinalizable()) {
3982 klass->SetFinalizable();
3983 }
3984
Elliott Hughes2da50362011-10-10 16:57:08 -07003985 // Inherit reference flags (if any) from the superclass.
3986 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
3987 if (reference_flags != 0) {
3988 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
3989 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003990 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07003991 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003992 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003993 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003994 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003995 return false;
3996 }
Elliott Hughes2da50362011-10-10 16:57:08 -07003997
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003998 if (kIsDebugBuild) {
3999 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004000 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004001 CHECK(super->IsResolved());
4002 super = super->GetSuperClass();
4003 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004004 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004005 return true;
4006}
4007
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004008// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004009bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004010 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4011 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004012 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004013 if (klass->IsInterface()) {
4014 // No vtable.
4015 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004016 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004017 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004018 return false;
4019 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004020 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004021 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004022 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004023 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4024 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004025 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004026 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004027}
4028
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004029// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4030// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4031// caches in the implementation below.
4032class MethodNameAndSignatureComparator FINAL : public ValueObject {
4033 public:
4034 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4035 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4036 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4037 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004038 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4039 }
4040
4041 const char* GetName() {
4042 if (name_ == nullptr) {
4043 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4044 }
4045 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004046 }
4047
4048 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4049 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4050 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4051 const DexFile* other_dex_file = other->GetDexFile();
4052 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4053 if (dex_file_ == other_dex_file) {
4054 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4055 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004056 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004057 uint32_t other_name_len;
4058 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4059 &other_name_len);
4060 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4061 return false;
4062 }
4063 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4064 }
4065
4066 private:
4067 // Dex file for the method to compare against.
4068 const DexFile* const dex_file_;
4069 // MethodId for the method to compare against.
4070 const DexFile::MethodId* const mid_;
4071 // Lazily computed name from the dex file's strings.
4072 const char* name_;
4073 // Lazily computed name length.
4074 uint32_t name_len_;
4075};
4076
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004077class LinkVirtualHashTable {
4078 public:
4079 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4080 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4081 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4082 }
4083 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4084 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4085 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004086 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004087 uint32_t index = hash % hash_size_;
4088 // Linear probe until we have an empty slot.
4089 while (hash_table_[index] != invalid_index_) {
4090 if (++index == hash_size_) {
4091 index = 0;
4092 }
4093 }
4094 hash_table_[index] = virtual_method_index;
4095 }
4096 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4097 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4098 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004099 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004100 size_t index = hash % hash_size_;
4101 while (true) {
4102 const uint32_t value = hash_table_[index];
4103 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4104 // the block and can safely assume not found.
4105 if (value == invalid_index_) {
4106 break;
4107 }
4108 if (value != removed_index_) { // This signifies not already overriden.
4109 mirror::ArtMethod* virtual_method =
4110 klass_->GetVirtualMethodDuringLinking(value);
4111 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4112 hash_table_[index] = removed_index_;
4113 return value;
4114 }
4115 }
4116 if (++index == hash_size_) {
4117 index = 0;
4118 }
4119 }
4120 return GetNotFoundIndex();
4121 }
4122 static uint32_t GetNotFoundIndex() {
4123 return invalid_index_;
4124 }
4125
4126 private:
4127 static const uint32_t invalid_index_;
4128 static const uint32_t removed_index_;
4129
4130 Handle<mirror::Class> klass_;
4131 const size_t hash_size_;
4132 uint32_t* const hash_table_;
4133};
4134
4135const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4136const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4137
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004138bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004139 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004140 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004141 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4142 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004143 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004144 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004145 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004146 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4147 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4148 if (UNLIKELY(vtable.Get() == nullptr)) {
4149 CHECK(self->IsExceptionPending()); // OOME.
4150 return false;
4151 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004152 for (size_t i = 0; i < super_vtable_length; i++) {
4153 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004154 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004155 if (num_virtual_methods == 0) {
4156 klass->SetVTable(vtable.Get());
4157 return true;
4158 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004159 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004160 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4161 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4162 if (num_virtual_methods == 0) {
4163 klass->SetVTable(super_vtable);
4164 return true;
4165 }
4166 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004167 if (UNLIKELY(vtable.Get() == nullptr)) {
4168 CHECK(self->IsExceptionPending()); // OOME.
4169 return false;
4170 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004171 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004172 // How the algorithm works:
4173 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4174 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4175 // method which has not been matched to a vtable method, and j if the virtual method at the
4176 // index overrode the super virtual method at index j.
4177 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4178 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4179 // the need for the initial vtable which we later shrink back down).
4180 // 3. Add non overridden methods to the end of the vtable.
4181 static constexpr size_t kMaxStackHash = 250;
4182 const size_t hash_table_size = num_virtual_methods * 3;
4183 uint32_t* hash_table_ptr;
4184 std::unique_ptr<uint32_t[]> hash_heap_storage;
4185 if (hash_table_size <= kMaxStackHash) {
4186 hash_table_ptr = reinterpret_cast<uint32_t*>(
4187 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4188 } else {
4189 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4190 hash_table_ptr = hash_heap_storage.get();
4191 }
4192 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4193 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004194 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004195 hash_table.Add(i);
4196 }
4197 // Loop through each super vtable method and see if they are overriden by a method we added to
4198 // the hash table.
4199 for (size_t j = 0; j < super_vtable_length; ++j) {
4200 // Search the hash table to see if we are overidden by any method.
4201 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4202 MethodNameAndSignatureComparator super_method_name_comparator(
4203 super_method->GetInterfaceMethodIfProxy());
4204 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4205 if (hash_index != hash_table.GetNotFoundIndex()) {
4206 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4207 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4208 super_method->GetAccessFlags())) {
4209 if (super_method->IsFinal()) {
4210 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4211 PrettyMethod(virtual_method).c_str(),
4212 super_method->GetDeclaringClassDescriptor());
4213 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004214 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004215 vtable->SetWithoutChecks<false>(j, virtual_method);
4216 virtual_method->SetMethodIndex(j);
4217 } else {
4218 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004219 << " would have incorrectly overridden the package-private method in "
4220 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004221 }
4222 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004223 }
4224 // Add the non overridden methods at the end.
4225 size_t actual_count = super_vtable_length;
4226 for (size_t i = 0; i < num_virtual_methods; ++i) {
4227 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4228 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4229 if (method_idx < super_vtable_length &&
4230 local_method == vtable->GetWithoutChecks(method_idx)) {
4231 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004232 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004233 vtable->SetWithoutChecks<false>(actual_count, local_method);
4234 local_method->SetMethodIndex(actual_count);
4235 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004236 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004237 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004238 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004239 return false;
4240 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004241 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004242 CHECK_LE(actual_count, max_count);
4243 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004244 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004245 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004246 CHECK(self->IsExceptionPending()); // OOME.
4247 return false;
4248 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004249 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004250 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004251 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004252 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004253 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004254 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4255 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004256 return false;
4257 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004258 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4259 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004260 CHECK(self->IsExceptionPending()); // OOME.
4261 return false;
4262 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004263 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004264 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004265 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004266 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004267 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004268 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004269 }
4270 return true;
4271}
4272
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004273bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4274 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4275 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004276 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004277 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004278 const bool has_superclass = klass->HasSuperClass();
4279 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4280 const bool have_interfaces = interfaces.Get() != nullptr;
4281 const size_t num_interfaces =
4282 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4283 if (num_interfaces == 0) {
4284 if (super_ifcount == 0) {
4285 // Class implements no interfaces.
4286 DCHECK_EQ(klass->GetIfTableCount(), 0);
4287 DCHECK(klass->GetIfTable() == nullptr);
4288 return true;
4289 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004290 // Class implements same interfaces as parent, are any of these not marker interfaces?
4291 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004292 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004293 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004294 if (super_iftable->GetMethodArrayCount(i) > 0) {
4295 has_non_marker_interface = true;
4296 break;
4297 }
4298 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004299 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004300 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004301 klass->SetIfTable(super_iftable);
4302 return true;
4303 }
4304 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004305 size_t ifcount = super_ifcount + num_interfaces;
4306 for (size_t i = 0; i < num_interfaces; i++) {
4307 mirror::Class* interface = have_interfaces ?
4308 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4309 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004310 if (UNLIKELY(!interface->IsInterface())) {
4311 std::string temp;
4312 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4313 PrettyDescriptor(klass.Get()).c_str(),
4314 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4315 return false;
4316 }
4317 ifcount += interface->GetIfTableCount();
4318 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004319 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004320 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004321 CHECK(self->IsExceptionPending()); // OOME.
4322 return false;
4323 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004324 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004325 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004326 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004327 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004328 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004329 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004330 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004331 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004332 // Flatten the interface inheritance hierarchy.
4333 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004334 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004335 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4336 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004337 // Check if interface is already in iftable
4338 bool duplicate = false;
4339 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004340 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004341 if (existing_interface == interface) {
4342 duplicate = true;
4343 break;
4344 }
4345 }
4346 if (!duplicate) {
4347 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004348 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004349 // Add this interface's non-duplicate super-interfaces.
4350 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004351 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004352 bool super_duplicate = false;
4353 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004354 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004355 if (existing_interface == super_interface) {
4356 super_duplicate = true;
4357 break;
4358 }
4359 }
4360 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004361 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004362 }
4363 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004364 }
4365 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004366 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004367 // Shrink iftable in case duplicates were found
4368 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004369 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004370 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004371 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004372 CHECK(self->IsExceptionPending()); // OOME.
4373 return false;
4374 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004375 ifcount = idx;
4376 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004377 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004378 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004379 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004380 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004381 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004382 return true;
4383 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004384 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004385 size_t max_miranda_methods = 0; // The max size of miranda_list.
4386 for (size_t i = 0; i < ifcount; ++i) {
4387 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4388 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004389 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004390 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004391 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4392 hs.NewHandle(klass->GetVTableDuringLinking()));
4393 // Copy the IMT from the super class if possible.
4394 bool extend_super_iftable = false;
4395 if (has_superclass) {
4396 mirror::Class* super_class = klass->GetSuperClass();
4397 extend_super_iftable = true;
4398 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4399 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4400 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4401 }
4402 } else {
4403 // No imt in the super class, need to reconstruct from the iftable.
4404 mirror::IfTable* if_table = super_class->GetIfTable();
4405 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4406 const size_t length = super_class->GetIfTableCount();
4407 for (size_t i = 0; i < length; ++i) {
4408 mirror::Class* interface = iftable->GetInterface(i);
4409 const size_t num_virtuals = interface->NumVirtualMethods();
4410 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4411 DCHECK_EQ(num_virtuals, method_array_count);
4412 if (method_array_count == 0) {
4413 continue;
4414 }
4415 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4416 for (size_t j = 0; j < num_virtuals; ++j) {
4417 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4418 if (method->IsMiranda()) {
4419 continue;
4420 }
4421 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4422 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4423 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4424 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4425 out_imt->SetReference(imt_index, method);
4426 } else if (imt_ref != conflict_method) {
4427 out_imt->SetReference(imt_index, conflict_method);
4428 }
4429 }
4430 }
4431 }
4432 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004433 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004434 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004435 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004436 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004437 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004438 const bool is_super = i < super_ifcount;
4439 const bool super_interface = is_super && extend_super_iftable;
4440 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4441 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4442 if (super_interface) {
4443 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4444 DCHECK(if_table != nullptr);
4445 DCHECK(if_table->GetMethodArray(i) != nullptr);
4446 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004447 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004448 AsObjectArray<mirror::ArtMethod>());
4449 // We are overwriting a super class interface, try to only virtual methods instead of the
4450 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004451 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004452 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004453 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004454 // A new interface, we need the whole vtable incase a new interface method is implemented
4455 // in the whole superclass.
4456 input_array = vtable;
4457 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004458 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004459 CHECK(self->IsExceptionPending()); // OOME.
4460 return false;
4461 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004462 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004463 if (input_array.Get() == nullptr) {
4464 // If the added virtual methods is empty, do nothing.
4465 DCHECK(super_interface);
4466 continue;
4467 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004468 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004469 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004470 MethodNameAndSignatureComparator interface_name_comparator(
4471 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07004472 int32_t k;
4473 // For each method listed in the interface's method list, find the
4474 // matching method in our class's method list. We want to favor the
4475 // subclass over the superclass, which just requires walking
4476 // back from the end of the vtable. (This only matters if the
4477 // superclass defines a private method and this class redefines
4478 // it -- otherwise it would use the same vtable slot. In .dex files
4479 // those don't end up in the virtual method table, so it shouldn't
4480 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004481 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4482 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004483 mirror::ArtMethod* vtable_method_for_name_comparison =
4484 vtable_method->GetInterfaceMethodIfProxy();
4485 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004486 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004487 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004488 ThrowIllegalAccessError(
4489 klass.Get(),
4490 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004491 PrettyMethod(vtable_method).c_str(),
4492 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004493 return false;
4494 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004495 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004496 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004497 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4498 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4499 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4500 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4501 out_imt->SetReference(imt_index, vtable_method);
4502 } else if (imt_ref != conflict_method) {
4503 // If we are not a conflict and we have the same signature and name as the imt entry,
4504 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004505 MethodNameAndSignatureComparator imt_ref_name_comparator(
4506 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004507 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004508 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004509 out_imt->SetReference(imt_index, vtable_method);
4510 } else {
4511 out_imt->SetReference(imt_index, conflict_method);
4512 }
Jeff Hao88474b42013-10-23 16:24:40 -07004513 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004514 break;
4515 }
4516 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004517 if (k < 0 && !super_interface) {
4518 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004519 for (size_t l = 0; l < miranda_list_size; ++l) {
4520 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004521 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004522 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07004523 break;
4524 }
4525 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004526 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004527 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004528 miranda_method = interface_method->Clone(self)->AsArtMethod();
4529 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004530 CHECK(self->IsExceptionPending()); // OOME.
4531 return false;
4532 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004533 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004534 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004535 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004536 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004537 }
4538 }
4539 }
4540 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004541 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004542 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004543 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004544 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4545 if (old_method_count == 0) {
4546 virtuals = AllocArtMethodArray(self, new_method_count);
4547 } else {
4548 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4549 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004550 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004551 CHECK(self->IsExceptionPending()); // OOME.
4552 return false;
4553 }
4554 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004555
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004556 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004557 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004558 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004559 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004560 CHECK(self->IsExceptionPending()); // OOME.
4561 return false;
4562 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004563 for (size_t i = 0; i < miranda_list_size; ++i) {
4564 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004565 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004566 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4567 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4568 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004569 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004570 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004571 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004572 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004573 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004574
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004575 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004576 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
4577 for (int i = 0; i < check_vtable->GetLength(); ++i) {
4578 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004579 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004580 }
4581
Ian Rogers7b078e82014-09-10 14:44:24 -07004582 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004583 return true;
4584}
4585
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004586bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004587 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004588 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004589}
4590
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004591bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004592 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004593 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004594}
4595
Brian Carlstromdbc05252011-09-09 01:59:59 -07004596struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004597 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4598 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004599 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07004600 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004601 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004602 // 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 -07004603 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4604 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004605 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00004606 if (type1 == Primitive::kPrimNot) {
4607 // Reference always goes first.
4608 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08004609 }
Vladimir Markod5777482014-11-12 17:02:02 +00004610 if (type2 == Primitive::kPrimNot) {
4611 // Reference always goes first.
4612 return false;
4613 }
4614 size_t size1 = Primitive::ComponentSize(type1);
4615 size_t size2 = Primitive::ComponentSize(type2);
4616 if (size1 != size2) {
4617 // Larger primitive types go first.
4618 return size1 > size2;
4619 }
4620 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
4621 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004622 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004623 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
4624 // by name and for equal names by type id index.
4625 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
4626 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004627 }
4628};
4629
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004630bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07004631 size_t* class_size) {
4632 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004633 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
4634 ArtField* const fields = is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004635
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004636 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004637 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004638 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00004639 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004640 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004641 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004642 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004643 CHECK(super_class->IsResolved())
4644 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004645 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004646 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004647 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004648
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004649 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004650
Brian Carlstromdbc05252011-09-09 01:59:59 -07004651 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004652 // minimizes disruption of C++ version such as Class and Method.
Mathieu Chartierc7853442015-03-27 14:35:38 -07004653 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07004654 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07004655 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07004656 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004657 grouped_and_sorted_fields.push_back(&fields[i]);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004658 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004659 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4660 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004661
Fred Shih381e4ca2014-08-25 17:24:27 -07004662 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07004663 size_t current_field = 0;
4664 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07004665 FieldGaps gaps;
4666
Brian Carlstromdbc05252011-09-09 01:59:59 -07004667 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004668 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004669 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004670 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004671 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004672 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004673 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004674 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
4675 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07004676 MemberOffset old_offset = field_offset;
4677 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
4678 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
4679 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004680 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07004681 grouped_and_sorted_fields.pop_front();
4682 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004683 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00004684 field_offset = MemberOffset(field_offset.Uint32Value() +
4685 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004686 }
Fred Shih381e4ca2014-08-25 17:24:27 -07004687 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
4688 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00004689 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4690 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4691 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4692 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07004693 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
4694 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07004695 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004696
Elliott Hughesadb460d2011-10-05 17:02:34 -07004697 // 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 -07004698 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004699 // We know there are no non-reference fields in the Reference classes, and we know
4700 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004701 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07004702 CHECK_STREQ(fields[num_fields - 1].GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004703 --num_reference_fields;
4704 }
4705
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004706 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004707 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004708 if (is_static) {
4709 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004710 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004711 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004712 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004713 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08004714 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08004715 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
4716 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08004717 } else {
4718 std::string temp;
4719 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
4720 size_t previous_size = klass->GetObjectSize();
4721 if (previous_size != 0) {
4722 // Make sure that we didn't originally have an incorrect size.
4723 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
4724 }
4725 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004726 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004727 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004728 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004729
4730 if (kIsDebugBuild) {
4731 // Make sure that the fields array is ordered by name but all reference
4732 // offsets are at the beginning as far as alignment allows.
4733 MemberOffset start_ref_offset = is_static
4734 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
4735 : klass->GetFirstReferenceInstanceFieldOffset();
4736 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
4737 num_reference_fields *
4738 sizeof(mirror::HeapReference<mirror::Object>));
4739 MemberOffset current_ref_offset = start_ref_offset;
4740 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004741 ArtField* field = &fields[i];
4742 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
4743 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
4744 << field->GetOffset();
Vladimir Marko76649e82014-11-10 18:32:59 +00004745 if (i != 0) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004746 ArtField* const prev_field = &fields[i - 1];
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004747 // NOTE: The field names can be the same. This is not possible in the Java language
4748 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
4749 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00004750 }
4751 Primitive::Type type = field->GetTypeAsPrimitiveType();
4752 bool is_primitive = type != Primitive::kPrimNot;
4753 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
4754 strcmp("referent", field->GetName()) == 0) {
4755 is_primitive = true; // We lied above, so we have to expect a lie here.
4756 }
4757 MemberOffset offset = field->GetOffsetDuringLinking();
4758 if (is_primitive) {
4759 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
4760 // Shuffled before references.
4761 size_t type_size = Primitive::ComponentSize(type);
4762 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
4763 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
4764 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
4765 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
4766 }
4767 } else {
4768 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
4769 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
4770 sizeof(mirror::HeapReference<mirror::Object>));
4771 }
4772 }
4773 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
4774 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004775 return true;
4776}
4777
Vladimir Marko76649e82014-11-10 18:32:59 +00004778// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004779void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004780 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004781 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004782 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004783 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004784 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004785 // Compute reference offsets unless our superclass overflowed.
4786 if (reference_offsets != mirror::Class::kClassWalkSuper) {
4787 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00004788 if (num_reference_fields != 0u) {
4789 // All of the fields that contain object references are guaranteed be grouped in memory
4790 // starting at an appropriately aligned address after super class object data.
4791 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
4792 sizeof(mirror::HeapReference<mirror::Object>));
4793 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004794 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00004795 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004796 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004797 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00004798 reference_offsets |= (0xffffffffu << start_bit) &
4799 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004800 }
4801 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07004802 }
4803 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07004804 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004805}
4806
Mathieu Chartier590fee92013-09-13 13:46:47 -07004807mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004808 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004809 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004810 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004811 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004812 return resolved;
4813 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004814 uint32_t utf16_length;
4815 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004816 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004817 dex_cache->SetResolvedString(string_idx, string);
4818 return string;
4819}
4820
Mathieu Chartier590fee92013-09-13 13:46:47 -07004821mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004822 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004823 StackHandleScope<2> hs(Thread::Current());
4824 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4825 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004826 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4827}
4828
4829mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004830 Handle<mirror::DexCache> dex_cache,
4831 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004832 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004833 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004834 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08004835 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004836 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004837 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004838 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004839 // TODO: we used to throw here if resolved's class loader was not the
4840 // boot class loader. This was to permit different classes with the
4841 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004842 dex_cache->SetResolvedType(type_idx, resolved);
4843 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004844 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004845 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004846 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004847 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004848 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004849 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004850 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004851 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004852 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004853 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004854 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004855 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004856 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004857 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004858 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004859 return resolved;
4860}
4861
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004862mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004863 Handle<mirror::DexCache> dex_cache,
4864 Handle<mirror::ClassLoader> class_loader,
4865 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004866 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004867 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004868 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004869 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004870 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004871 return resolved;
4872 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004873 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004874 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004875 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004876 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004877 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004878 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004879 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004880 // Scan using method_idx, this saves string compares but will only hit for matching dex
4881 // caches/files.
4882 switch (type) {
4883 case kDirect: // Fall-through.
4884 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004885 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004886 break;
4887 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004888 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004889 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004890 break;
4891 case kSuper: // Fall-through.
4892 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004893 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004894 break;
4895 default:
4896 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07004897 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004898 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004899 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004900 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004901 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004902 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004903 switch (type) {
4904 case kDirect: // Fall-through.
4905 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004906 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004907 break;
4908 case kInterface:
4909 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004910 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004911 break;
4912 case kSuper: // Fall-through.
4913 case kVirtual:
4914 resolved = klass->FindVirtualMethod(name, signature);
4915 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004916 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004917 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004918 // If we found a method, check for incompatible class changes.
4919 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004920 // Be a good citizen and update the dex cache to speed subsequent calls.
4921 dex_cache->SetResolvedMethod(method_idx, resolved);
4922 return resolved;
4923 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004924 // If we had a method, it's an incompatible-class-change error.
4925 if (resolved != nullptr) {
4926 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
4927 } else {
4928 // We failed to find the method which means either an access error, an incompatible class
4929 // change, or no such method. First try to find the method among direct and virtual methods.
4930 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4931 const Signature signature = dex_file.GetMethodSignature(method_id);
4932 switch (type) {
4933 case kDirect:
4934 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004935 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004936 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
4937 // have had a resolved method before, which triggers the "true" branch above.
4938 break;
4939 case kInterface:
4940 case kVirtual:
4941 case kSuper:
4942 resolved = klass->FindDirectMethod(name, signature);
4943 break;
4944 }
4945
4946 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08004947 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004948 if (resolved != nullptr && referrer.Get() != nullptr) {
4949 mirror::Class* methods_class = resolved->GetDeclaringClass();
4950 mirror::Class* referring_class = referrer->GetDeclaringClass();
4951 if (!referring_class->CanAccess(methods_class)) {
4952 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4953 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004954 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004955 } else if (!referring_class->CanAccessMember(methods_class,
4956 resolved->GetAccessFlags())) {
4957 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004958 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004959 }
4960 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004961 if (!exception_generated) {
4962 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
4963 // interface methods and throw if we find the method there. If we find nothing, throw a
4964 // NoSuchMethodError.
4965 switch (type) {
4966 case kDirect:
4967 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004968 if (resolved != nullptr) {
4969 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4970 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004971 resolved = klass->FindInterfaceMethod(name, signature);
4972 if (resolved != nullptr) {
4973 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4974 } else {
4975 ThrowNoSuchMethodError(type, klass, name, signature);
4976 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004977 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004978 break;
4979 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004980 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004981 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4982 } else {
4983 resolved = klass->FindVirtualMethod(name, signature);
4984 if (resolved != nullptr) {
4985 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4986 } else {
4987 ThrowNoSuchMethodError(type, klass, name, signature);
4988 }
4989 }
4990 break;
4991 case kSuper:
4992 if (resolved != nullptr) {
4993 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004994 } else {
4995 ThrowNoSuchMethodError(type, klass, name, signature);
4996 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004997 break;
4998 case kVirtual:
4999 if (resolved != nullptr) {
5000 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5001 } else {
5002 resolved = klass->FindInterfaceMethod(name, signature);
5003 if (resolved != nullptr) {
5004 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5005 } else {
5006 ThrowNoSuchMethodError(type, klass, name, signature);
5007 }
5008 }
5009 break;
5010 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005011 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005012 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005013 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005014 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005015 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005016}
5017
Mathieu Chartierc7853442015-03-27 14:35:38 -07005018ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
5019 Handle<mirror::DexCache> dex_cache,
5020 Handle<mirror::ClassLoader> class_loader, bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005021 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005022 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005023 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005024 return resolved;
5025 }
5026 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005027 Thread* const self = Thread::Current();
5028 StackHandleScope<1> hs(self);
5029 Handle<mirror::Class> klass(
5030 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005031 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005032 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005033 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005034 }
5035
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005036 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005037 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005038 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005039 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005040 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005041
Andreas Gampe58a5af82014-07-31 16:23:49 -07005042 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005043 const char* name = dex_file.GetFieldName(field_id);
5044 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5045 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005046 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005047 } else {
5048 resolved = klass->FindInstanceField(name, type);
5049 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005050 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005051 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005052 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005053 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005054 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07005055 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08005056 return resolved;
5057}
5058
Mathieu Chartierc7853442015-03-27 14:35:38 -07005059ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, uint32_t field_idx,
5060 Handle<mirror::DexCache> dex_cache,
5061 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005062 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005063 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005064 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005065 return resolved;
5066 }
5067 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005068 Thread* self = Thread::Current();
5069 StackHandleScope<1> hs(self);
5070 Handle<mirror::Class> klass(
5071 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005072 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005073 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005074 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005075 }
5076
Ian Rogersdfb325e2013-10-30 01:00:44 -07005077 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5078 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005079 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005080 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005081 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005082 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08005083 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005084 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005085 }
5086 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005087}
5088
Brian Carlstromea46f952013-07-30 01:26:50 -07005089const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005090 uint32_t* length) {
5091 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5092 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005093 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005094 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005095 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005096}
5097
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005098void ClassLinker::DumpAllClasses(int flags) {
5099 if (dex_cache_image_class_lookup_required_) {
5100 MoveImageClassesToClassTable();
5101 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005102 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5103 // 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 -08005104 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005105 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005106 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005107 for (GcRoot<mirror::Class>& it : class_table_) {
5108 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005109 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005110 }
5111
5112 for (size_t i = 0; i < all_classes.size(); ++i) {
5113 all_classes[i]->DumpClass(std::cerr, flags);
5114 }
5115}
5116
Elliott Hughes956af0f2014-12-11 14:34:28 -08005117static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005118 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005119 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5120 base -= sizeof(void*); // Move backward so that code_offset != 0.
5121 const uint32_t code_offset = sizeof(void*);
5122 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005123}
5124
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005125bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5126 return (entry_point == GetQuickResolutionStub()) ||
5127 (quick_resolution_trampoline_ == entry_point);
5128}
5129
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005130bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5131 return (entry_point == GetQuickToInterpreterBridge()) ||
5132 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5133}
5134
5135bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5136 return (entry_point == GetQuickGenericJniStub()) ||
5137 (quick_generic_jni_trampoline_ == entry_point);
5138}
5139
5140const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5141 return GetQuickGenericJniStub();
5142}
5143
Elliott Hughes956af0f2014-12-11 14:34:28 -08005144void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5145 const void* method_code) const {
5146 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005147 oat_method.LinkMethod(method);
5148 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005149}
5150
5151void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5152 if (!method->IsNative()) {
5153 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005154 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5155 } else {
5156 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005157 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005158 oat_method.LinkMethod(method);
5159 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005160 }
5161}
5162
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005163void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005164 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005165 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005166 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005167 MoveImageClassesToClassTable();
5168 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005169 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005170 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5171 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005172}
5173
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005174size_t ClassLinker::NumLoadedClasses() {
5175 if (dex_cache_image_class_lookup_required_) {
5176 MoveImageClassesToClassTable();
5177 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005178 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005179 // Only return non zygote classes since these are the ones which apps which care about.
5180 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005181}
5182
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005183pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005184 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005185}
5186
5187pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005188 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005189}
5190
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005191void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005192 DCHECK(!init_done_);
5193
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005194 DCHECK(klass != nullptr);
5195 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005196
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005197 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005198 DCHECK(class_roots != nullptr);
5199 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005200 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005201}
5202
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005203const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5204 static const char* class_roots_descriptors[] = {
5205 "Ljava/lang/Class;",
5206 "Ljava/lang/Object;",
5207 "[Ljava/lang/Class;",
5208 "[Ljava/lang/Object;",
5209 "Ljava/lang/String;",
5210 "Ljava/lang/DexCache;",
5211 "Ljava/lang/ref/Reference;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005212 "Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005213 "Ljava/lang/reflect/Field;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005214 "Ljava/lang/reflect/Proxy;",
5215 "[Ljava/lang/String;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005216 "[Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005217 "[Ljava/lang/reflect/Field;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005218 "Ljava/lang/ClassLoader;",
5219 "Ljava/lang/Throwable;",
5220 "Ljava/lang/ClassNotFoundException;",
5221 "Ljava/lang/StackTraceElement;",
5222 "Z",
5223 "B",
5224 "C",
5225 "D",
5226 "F",
5227 "I",
5228 "J",
5229 "S",
5230 "V",
5231 "[Z",
5232 "[B",
5233 "[C",
5234 "[D",
5235 "[F",
5236 "[I",
5237 "[J",
5238 "[S",
5239 "[Ljava/lang/StackTraceElement;",
5240 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005241 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5242 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005243
5244 const char* descriptor = class_roots_descriptors[class_root];
5245 CHECK(descriptor != nullptr);
5246 return descriptor;
5247}
5248
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005249std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5250 const {
5251 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005252 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005253}
5254
5255bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005256 const GcRoot<mirror::Class>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005257 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5258 return false;
5259 }
5260 std::string temp;
5261 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5262}
5263
5264std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5265 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005266 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005267}
5268
5269bool ClassLinker::ClassDescriptorHashEquals::operator()(
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005270 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005271 if (a.Read()->GetClassLoader() != b.second) {
5272 return false;
5273 }
5274 return a.Read()->DescriptorEquals(b.first);
5275}
5276
5277bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005278 const char* descriptor) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005279 return a.Read()->DescriptorEquals(descriptor);
5280}
5281
5282std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005283 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005284}
5285
Sebastien Hertz6963e442014-11-26 22:11:27 +01005286bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07005287 if (Runtime::Current()->UseJit()) {
5288 // JIT can have direct code pointers from any method to any other method.
5289 return true;
5290 }
Sebastien Hertz6963e442014-11-26 22:11:27 +01005291 // Non-image methods don't use direct code pointer.
5292 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5293 return false;
5294 }
5295 if (m->IsPrivate()) {
5296 // The method can only be called inside its own oat file. Therefore it won't be called using
5297 // its direct code if the oat file has been compiled in PIC mode.
Sebastien Hertz6963e442014-11-26 22:11:27 +01005298 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
Richard Uhler07b3c232015-03-31 15:57:54 -07005299 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01005300 if (oat_dex_file == nullptr) {
5301 // No oat file: the method has not been compiled.
5302 return false;
5303 }
5304 const OatFile* oat_file = oat_dex_file->GetOatFile();
5305 return oat_file != nullptr && !oat_file->IsPic();
5306 } else {
5307 // The method can be called outside its own oat file. Therefore it won't be called using its
5308 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5309 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5310 for (const OatFile* oat_file : oat_files_) {
5311 if (!oat_file->IsPic()) {
5312 return true;
5313 }
5314 }
5315 return false;
5316 }
5317}
5318
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005319jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
5320 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
5321 // We could move the jobject to the callers, but all call-sites do this...
5322 ScopedObjectAccessUnchecked soa(self);
5323
5324 // Register the dex files.
5325 for (const DexFile* dex_file : dex_files) {
5326 RegisterDexFile(*dex_file);
5327 }
5328
5329 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005330 StackHandleScope<10> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005331
Mathieu Chartierc7853442015-03-27 14:35:38 -07005332 ArtField* dex_elements_field =
5333 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005334
Mathieu Chartierc7853442015-03-27 14:35:38 -07005335 mirror::Class* dex_elements_class = dex_elements_field->GetType<true>();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005336 DCHECK(dex_elements_class != nullptr);
5337 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005338 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
5339 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005340 Handle<mirror::Class> h_dex_element_class =
5341 hs.NewHandle(dex_elements_class->GetComponentType());
5342
Mathieu Chartierc7853442015-03-27 14:35:38 -07005343 ArtField* element_file_field =
5344 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
5345 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005346
Mathieu Chartierc7853442015-03-27 14:35:38 -07005347 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
5348 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005349
5350 // Fill the elements array.
5351 int32_t index = 0;
5352 for (const DexFile* dex_file : dex_files) {
5353 StackHandleScope<3> hs2(self);
5354
5355 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(self, 1));
5356 DCHECK(h_long_array.Get() != nullptr);
5357 h_long_array->Set(0, reinterpret_cast<intptr_t>(dex_file));
5358
5359 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07005360 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005361 DCHECK(h_dex_file.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005362 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005363
5364 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
5365 DCHECK(h_element.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005366 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005367
5368 h_dex_elements->Set(index, h_element.Get());
5369 index++;
5370 }
5371 DCHECK_EQ(index, h_dex_elements->GetLength());
5372
5373 // Create DexPathList.
5374 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07005375 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005376 DCHECK(h_dex_path_list.Get() != nullptr);
5377 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005378 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005379
5380 // Create PathClassLoader.
5381 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
5382 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
5383 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
5384 h_path_class_class->AllocObject(self));
5385 DCHECK(h_path_class_loader.Get() != nullptr);
5386 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005387 ArtField* path_list_field =
5388 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
5389 DCHECK(path_list_field != nullptr);
5390 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005391
5392 // Make a pretend boot-classpath.
5393 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07005394 ArtField* const parent_field =
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005395 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07005396 "Ljava/lang/ClassLoader;");
5397 DCHECK(parent_field!= nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005398 mirror::Object* boot_cl =
5399 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005400 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005401
5402 // Make it a global ref and return.
5403 ScopedLocalRef<jobject> local_ref(
5404 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
5405 return soa.Env()->NewGlobalRef(local_ref.get());
5406}
5407
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005408} // namespace art