blob: 935c4018258248c5339cdbec512871f3c8b2536d [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
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001262mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1263 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001264 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001265 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08001266 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001267 if (class_loader->GetClass() !=
1268 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
1269 class_loader->GetParent()->GetClass() !=
1270 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
1271 return nullptr;
1272 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001273 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001274 // Check if this would be found in the parent boot class loader.
1275 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001276 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001277 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08001278 // May return null if resolution on another thread fails.
1279 klass = EnsureResolved(self, descriptor, klass);
1280 } else {
1281 // May OOME.
1282 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
1283 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001284 }
Ian Rogers32427292014-11-19 14:05:21 -08001285 if (klass == nullptr) {
1286 CHECK(self->IsExceptionPending()) << descriptor;
1287 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001288 }
Ian Rogers32427292014-11-19 14:05:21 -08001289 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001290 } else {
Ian Rogers32427292014-11-19 14:05:21 -08001291 // Handle as if this is the child PathClassLoader.
1292 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001293 StackHandleScope<3> hs(self);
1294 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1295 // We need to get the DexPathList and loop through it.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001296 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
1297 ArtField* const dex_file_field =
1298 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001299 mirror::Object* dex_path_list =
1300 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1301 GetObject(class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07001302 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001303 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1304 mirror::Object* dex_elements_obj =
1305 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1306 GetObject(dex_path_list);
1307 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1308 // at the mCookie which is a DexFile vector.
1309 if (dex_elements_obj != nullptr) {
1310 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1311 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1312 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1313 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1314 if (element == nullptr) {
1315 // Should never happen, fall back to java code to throw a NPE.
1316 break;
1317 }
1318 mirror::Object* dex_file = dex_file_field->GetObject(element);
1319 if (dex_file != nullptr) {
Andreas Gampe324b9bb2015-02-23 16:33:22 -08001320 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1321 if (long_array == nullptr) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001322 // This should never happen so log a warning.
1323 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
1324 break;
1325 }
Andreas Gampe324b9bb2015-02-23 16:33:22 -08001326 int32_t long_array_size = long_array->GetLength();
1327 for (int32_t j = 0; j < long_array_size; ++j) {
1328 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1329 long_array->GetWithoutChecks(j)));
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001330 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001331 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001332 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001333 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
1334 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001335 if (klass == nullptr) {
1336 CHECK(self->IsExceptionPending()) << descriptor;
1337 self->ClearException();
1338 return nullptr;
1339 }
1340 return klass;
1341 }
1342 }
1343 }
1344 }
1345 }
1346 }
Ian Rogers32427292014-11-19 14:05:21 -08001347 self->AssertNoPendingException();
1348 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001349 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001350}
1351
Ian Rogers98379392014-02-24 16:53:16 -08001352mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001353 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001354 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001355 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001356 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001357 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001358 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1359 // for primitive classes that aren't backed by dex files.
1360 return FindPrimitiveClass(descriptor[0]);
1361 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001362 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001363 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001364 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001365 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001366 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001367 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001368 // Class is not yet loaded.
1369 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001370 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001371 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001372 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001373 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001374 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001375 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001376 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001377 } else {
1378 // The boot class loader is searched ahead of the application class loader, failures are
1379 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1380 // trigger the chaining with a proper stack trace.
1381 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001382 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001383 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001384 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001385 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001386 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001387 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
1388 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001389 if (cp_klass != nullptr) {
1390 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001391 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001392
1393 if (Runtime::Current()->IsAotCompiler()) {
1394 // Oops, compile-time, can't run actual class-loader code.
1395 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
1396 self->SetException(pre_allocated);
1397 return nullptr;
1398 }
1399
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001400 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001401 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001402 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001403 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001404 {
1405 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001406 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1407 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001408 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001409 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001410 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001411 }
Ian Rogers68b56852014-08-29 20:19:11 -07001412 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001413 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1414 WellKnownClasses::java_lang_ClassLoader_loadClass,
1415 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001416 }
Ian Rogers98379392014-02-24 16:53:16 -08001417 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001418 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001419 return nullptr;
1420 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001421 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001422 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
1423 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001424 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001425 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001426 // success, return mirror::Class*
1427 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001428 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001429 }
Ian Rogers07140832014-09-30 15:43:59 -07001430 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001431}
1432
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001433mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001434 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001435 const DexFile& dex_file,
1436 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001437 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001438 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001439
Brian Carlstromaded5f72011-10-07 17:15:04 -07001440 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001441 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001442 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001443 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001444 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001445 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001446 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001447 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001448 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001449 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1450 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001451 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001452 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001453 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001454 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001455 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001456 }
1457
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001458 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001459 // Allocate a class with the status of not ready.
1460 // Interface object should get the right size here. Regular class will
1461 // figure out the right size later and be replaced with one of the right
1462 // size when the class becomes resolved.
1463 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001464 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001465 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001466 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001467 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001468 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001469 klass->SetDexCache(FindDexCache(dex_file));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001470
1471 SetupClass(dex_file, dex_class_def, klass, class_loader.Get());
1472
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001473 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001474 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001475
Mathieu Chartier590fee92013-09-13 13:46:47 -07001476 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001477 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001478 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001479 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1480 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001481 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001482 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001483
Mathieu Chartierc7853442015-03-27 14:35:38 -07001484 // Load the fields and other things after we are inserted in the table. This is so that we don't
1485 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
1486 // other reason is that the field roots are only visited from the class table. So we need to be
1487 // inserted before we allocate / fill in these fields.
1488 LoadClass(self, dex_file, dex_class_def, klass);
1489 if (self->IsExceptionPending()) {
1490 // An exception occured during load, set status to erroneous while holding klass' lock in case
1491 // notification is necessary.
1492 if (!klass->IsErroneous()) {
1493 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
1494 }
1495 return nullptr;
1496 }
1497
Brian Carlstromaded5f72011-10-07 17:15:04 -07001498 // Finish loading (if necessary) by finding parents
1499 CHECK(!klass->IsLoaded());
1500 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1501 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001502 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001503 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001504 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001505 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001506 }
1507 CHECK(klass->IsLoaded());
1508 // Link the class (if necessary)
1509 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001510 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001511 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001512
1513 mirror::Class* new_class = nullptr;
1514 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001515 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001516 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001517 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001518 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001519 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001520 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001521 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001522 CHECK(new_class != nullptr) << descriptor;
1523 CHECK(new_class->IsResolved()) << descriptor;
1524
1525 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001526
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001527 // Instrumentation may have updated entrypoints for all methods of all
1528 // classes. However it could not update methods of this class while we
1529 // were loading it. Now the class is resolved, we can update entrypoints
1530 // as required by instrumentation.
1531 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1532 // We must be in the kRunnable state to prevent instrumentation from
1533 // suspending all threads to update entrypoints while we are doing it
1534 // for this class.
1535 DCHECK_EQ(self->GetState(), kRunnable);
1536 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
1537 }
1538
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001539 /*
1540 * We send CLASS_PREPARE events to the debugger from here. The
1541 * definition of "preparation" is creating the static fields for a
1542 * class and initializing them to the standard default values, but not
1543 * executing any code (that comes later, during "initialization").
1544 *
1545 * We did the static preparation in LinkClass.
1546 *
1547 * The class has been prepared and resolved but possibly not yet verified
1548 * at this point.
1549 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001550 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001551
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001552 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001553}
1554
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001555uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1556 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001557 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001558 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001559 size_t num_8 = 0;
1560 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001561 size_t num_32 = 0;
1562 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001563 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001564 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1565 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001566 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001567 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001568 switch (c) {
1569 case 'L':
1570 case '[':
1571 num_ref++;
1572 break;
1573 case 'J':
1574 case 'D':
1575 num_64++;
1576 break;
1577 case 'I':
1578 case 'F':
1579 num_32++;
1580 break;
1581 case 'S':
1582 case 'C':
1583 num_16++;
1584 break;
1585 case 'B':
1586 case 'Z':
1587 num_8++;
1588 break;
1589 default:
1590 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001591 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001592 }
1593 }
1594 }
Fred Shih37f05ef2014-07-16 18:38:08 -07001595 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001596}
1597
Ian Rogers97b52f82014-08-14 11:34:07 -07001598OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
1599 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001600 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Richard Uhler07b3c232015-03-31 15:57:54 -07001601 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001602 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001603 *found = false;
1604 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001605 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001606 *found = true;
1607 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001608}
1609
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001610static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
1611 uint32_t method_idx) {
1612 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001613 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001614 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001615 ClassDataItemIterator it(dex_file, class_data);
1616 // Skip fields
1617 while (it.HasNextStaticField()) {
1618 it.Next();
1619 }
1620 while (it.HasNextInstanceField()) {
1621 it.Next();
1622 }
1623 // Process methods
1624 size_t class_def_method_index = 0;
1625 while (it.HasNextDirectMethod()) {
1626 if (it.GetMemberIndex() == method_idx) {
1627 return class_def_method_index;
1628 }
1629 class_def_method_index++;
1630 it.Next();
1631 }
1632 while (it.HasNextVirtualMethod()) {
1633 if (it.GetMemberIndex() == method_idx) {
1634 return class_def_method_index;
1635 }
1636 class_def_method_index++;
1637 it.Next();
1638 }
1639 DCHECK(!it.HasNext());
1640 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001641 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001642}
1643
Ian Rogers97b52f82014-08-14 11:34:07 -07001644const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001645 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001646 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001647 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001648 size_t oat_method_index;
1649 if (method->IsStatic() || method->IsDirect()) {
1650 // Simple case where the oat method index was stashed at load time.
1651 oat_method_index = method->GetMethodIndex();
1652 } else {
1653 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1654 // by search for its position in the declared virtual methods.
1655 oat_method_index = declaring_class->NumDirectMethods();
1656 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001657 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001658 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001659 // Check method index instead of identity in case of duplicate method definitions.
1660 if (method->GetDexMethodIndex() ==
1661 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001662 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001663 break;
1664 }
Ian Rogersf320b632012-03-13 18:47:47 -07001665 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001666 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001667 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1668 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001669 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001670 DCHECK_EQ(oat_method_index,
1671 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001672 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001673 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001674 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1675 declaring_class->GetDexClassDefIndex(),
1676 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001677 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001678 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001679 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001680 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001681}
1682
1683// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001684const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001685 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001686 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001687 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001688 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001689 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001690 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1691 if (found) {
1692 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001693 if (code != nullptr) {
1694 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001695 }
1696 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001697 jit::Jit* const jit = Runtime::Current()->GetJit();
1698 if (jit != nullptr) {
1699 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001700 if (code != nullptr) {
1701 return code;
1702 }
1703 }
1704 if (method->IsNative()) {
1705 // No code and native? Use generic trampoline.
1706 return GetQuickGenericJniStub();
1707 }
1708 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001709}
1710
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001711const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
1712 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1713 return nullptr;
1714 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001715 bool found;
1716 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1717 if (found) {
1718 return oat_method.GetQuickCode();
1719 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001720 jit::Jit* jit = Runtime::Current()->GetJit();
1721 if (jit != nullptr) {
1722 auto* code = jit->GetCodeCache()->GetCodeFor(method);
1723 if (code != nullptr) {
1724 return code;
1725 }
1726 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001727 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001728}
1729
Ian Rogersef7d42f2014-01-06 12:55:46 -08001730const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1731 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001732 bool found;
1733 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
1734 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001735 return nullptr;
1736 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001737 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001738 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001739}
1740
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001741// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001742static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07001743 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001744 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001745 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08001746 // May return true for native code, in the case of generic JNI
1747 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001748 return true;
1749 }
1750 // If interpreter mode is enabled, every method (except native and proxy) must
1751 // be run with interpreter.
1752 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1753 !method->IsNative() && !method->IsProxyMethod();
1754}
1755
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001756void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08001757 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07001758 if (klass->NumDirectMethods() == 0) {
1759 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08001760 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001761 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001762 if (!runtime->IsStarted()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001763 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001764 return; // OAT file unavailable.
1765 }
Ian Rogers19846512012-02-24 11:42:47 -08001766 }
Alex Light64ad14d2014-08-19 14:23:13 -07001767
Mathieu Chartierf8322842014-05-16 10:59:25 -07001768 const DexFile& dex_file = klass->GetDexFile();
1769 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07001770 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07001771 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07001772 // There should always be class data if there were direct methods.
1773 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08001774 ClassDataItemIterator it(dex_file, class_data);
1775 // Skip fields
1776 while (it.HasNextStaticField()) {
1777 it.Next();
1778 }
1779 while (it.HasNextInstanceField()) {
1780 it.Next();
1781 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001782 bool has_oat_class;
1783 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1784 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07001785 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001786 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001787 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001788 if (!method->IsStatic()) {
1789 // Only update static methods.
1790 continue;
Ian Rogers19846512012-02-24 11:42:47 -08001791 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001792 const void* quick_code = nullptr;
1793 if (has_oat_class) {
1794 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001795 quick_code = oat_method.GetQuickCode();
1796 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001797 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001798 if (enter_interpreter) {
1799 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07001800 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001801 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001802 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08001803 } else {
1804 quick_code = GetQuickToInterpreterBridge();
1805 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001806 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001807 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08001808 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001809 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08001810}
1811
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001812void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07001813 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001814 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001815 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001816 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001817 // The following code only applies to a non-compiler runtime.
1818 return;
1819 }
Ian Rogers62d6c772013-02-27 08:32:07 -08001820 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001821 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001822 if (oat_class != nullptr) {
1823 // Every kind of method should at least get an invoke stub from the oat_method.
1824 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001825 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001826 oat_method.LinkMethod(method.Get());
1827 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001828
Jeff Hao16743632013-05-08 10:59:04 -07001829 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001830 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08001831 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001832 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001833 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001834 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07001835 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07001836 }
1837
Brian Carlstrom92827a52011-10-10 15:50:01 -07001838 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001839 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001840 return;
1841 }
Ian Rogers19846512012-02-24 11:42:47 -08001842
1843 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001844 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001845 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
1846 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001847 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001848 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001849 if (!method->IsNative()) {
1850 // Set entry point from compiled code if there's no code or in interpreter only mode.
1851 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001852 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001853 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08001854 }
Ian Rogers0d6de042012-02-29 08:50:26 -08001855 }
jeffhao26c0a1a2012-01-17 16:28:33 -08001856
Ian Rogers62d6c772013-02-27 08:32:07 -08001857 if (method->IsNative()) {
1858 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001859 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07001860
1861 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001862 // We have a native method here without code. Then it should have either the generic JNI
1863 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
1864 // TODO: this doesn't handle all the cases where trampolines may be installed.
1865 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
1866 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07001867 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07001868 }
1869}
1870
Mathieu Chartierc7853442015-03-27 14:35:38 -07001871void ClassLinker::SetupClass(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1872 Handle<mirror::Class> klass, mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001873 CHECK(klass.Get() != nullptr);
1874 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001875 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001876 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001877 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001878
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001879 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07001880 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07001881 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001882 klass->SetAccessFlags(access_flags);
1883 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001884 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001885 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001886
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001887 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001888 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08001889 CHECK(klass->GetDexCacheStrings() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001890}
Brian Carlstrom934486c2011-07-12 23:42:50 -07001891
Mathieu Chartierc7853442015-03-27 14:35:38 -07001892void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
1893 const DexFile::ClassDef& dex_class_def,
1894 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07001895 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001896 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001897 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001898 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001899 bool has_oat_class = false;
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001900 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001901 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
1902 &has_oat_class);
1903 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001904 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07001905 }
1906 }
1907 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001908 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001909 }
1910}
1911
Mathieu Chartierc7853442015-03-27 14:35:38 -07001912ArtField* ClassLinker::AllocArtFieldArray(Thread* self, size_t length) {
1913 auto* const la = Runtime::Current()->GetLinearAlloc();
1914 auto* ptr = reinterpret_cast<ArtField*>(la->AllocArray<ArtField>(self, length));
1915 CHECK(ptr!= nullptr);
1916 std::uninitialized_fill_n(ptr, length, ArtField());
1917 return ptr;
1918}
1919
Ian Rogers7b078e82014-09-10 14:44:24 -07001920void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07001921 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001922 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001923 const OatFile::OatClass* oat_class) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001924 // Load static fields.
Ian Rogers0571d352011-11-03 19:51:38 -07001925 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001926 const size_t num_sfields = it.NumStaticFields();
1927 ArtField* sfields = num_sfields != 0 ? AllocArtFieldArray(self, num_sfields) : nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001928 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001929 CHECK_LT(i, num_sfields);
Ian Rogers7b078e82014-09-10 14:44:24 -07001930 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001931 LoadField(it, klass, &sfields[i]);
Ian Rogers0571d352011-11-03 19:51:38 -07001932 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001933 klass->SetSFields(sfields);
1934 klass->SetNumStaticFields(num_sfields);
1935 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
1936 // Load instance fields.
1937 const size_t num_ifields = it.NumInstanceFields();
1938 ArtField* ifields = num_ifields != 0 ? AllocArtFieldArray(self, num_ifields) : nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07001939 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001940 CHECK_LT(i, num_ifields);
Ian Rogers7b078e82014-09-10 14:44:24 -07001941 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001942 LoadField(it, klass, &ifields[i]);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001943 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001944 klass->SetIFields(ifields);
1945 klass->SetNumInstanceFields(num_ifields);
1946 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001947
Ian Rogers0571d352011-11-03 19:51:38 -07001948 // Load methods.
1949 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001950 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001951 mirror::ObjectArray<mirror::ArtMethod>* directs =
1952 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001953 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001954 CHECK(self->IsExceptionPending()); // OOME.
1955 return;
1956 }
1957 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001958 }
Ian Rogers0571d352011-11-03 19:51:38 -07001959 if (it.NumVirtualMethods() != 0) {
1960 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07001961 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
1962 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001963 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001964 CHECK(self->IsExceptionPending()); // OOME.
1965 return;
1966 }
1967 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001968 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001969 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07001970 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
1971 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001972 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001973 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001974 StackHandleScope<1> hs(self);
1975 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001976 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001977 CHECK(self->IsExceptionPending()); // OOME.
1978 return;
1979 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001980 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001981 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07001982 uint32_t it_method_index = it.GetMemberIndex();
1983 if (last_dex_method_index == it_method_index) {
1984 // duplicate case
1985 method->SetMethodIndex(last_class_def_method_index);
1986 } else {
1987 method->SetMethodIndex(class_def_method_index);
1988 last_dex_method_index = it_method_index;
1989 last_class_def_method_index = class_def_method_index;
1990 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08001991 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07001992 }
1993 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07001994 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001995 StackHandleScope<1> hs(self);
1996 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001997 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001998 CHECK(self->IsExceptionPending()); // OOME.
1999 return;
2000 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002001 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002002 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002003 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002004 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002005 }
2006 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002007}
2008
Mathieu Chartierc7853442015-03-27 14:35:38 -07002009void ClassLinker::LoadField(const ClassDataItemIterator& it, Handle<mirror::Class> klass,
2010 ArtField* dst) {
2011 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002012 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002013 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002014 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002015}
2016
Brian Carlstromea46f952013-07-30 01:26:50 -07002017mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002018 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002019 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002020 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002021 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002022 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002023
Brian Carlstromea46f952013-07-30 01:26:50 -07002024 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002025 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002026 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002027 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002028 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002029 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002030
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002031 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002032 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002033 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002034 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002035
Ian Rogers19846512012-02-24 11:42:47 -08002036 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002037 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002038
Andreas Gampe51829322014-08-25 15:05:04 -07002039 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002040
Ian Rogersdfb325e2013-10-30 01:00:44 -07002041 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002042 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002043 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2044 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002045 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002046 klass->SetFinalizable();
2047 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002048 std::string temp;
2049 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002050 // The Enum class declares a "final" finalize() method to prevent subclasses from
2051 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2052 // subclasses, so we exclude it here.
2053 // We also want to avoid setting the flag on Object, where we know that finalize() is
2054 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002055 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2056 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002057 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002058 }
2059 }
2060 }
2061 } else if (method_name[0] == '<') {
2062 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002063 bool is_init = (strcmp("<init>", method_name) == 0);
2064 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002065 if (UNLIKELY(!is_init && !is_clinit)) {
2066 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2067 } else {
2068 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2069 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002070 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002071 access_flags |= kAccConstructor;
2072 }
2073 }
2074 }
2075 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002076
Mathieu Chartier66f19252012-09-18 08:57:04 -07002077 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002078}
2079
Ian Rogers7b078e82014-09-10 14:44:24 -07002080void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002081 StackHandleScope<1> hs(self);
2082 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002083 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2084 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002085 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002086}
2087
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002088void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002089 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002090 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002091 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002092 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002093}
2094
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002095bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002096 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002097 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002098 mirror::DexCache* dex_cache = GetDexCache(i);
2099 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002100 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002101 }
2102 }
2103 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002104}
2105
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002106bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002107 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002108 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002109}
2110
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002111void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002112 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002113 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002114 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002115 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2116 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002117 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002118 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002119 if (log_new_dex_caches_roots_) {
2120 // TODO: This is not safe if we can remove dex caches.
2121 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2122 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002123}
2124
Brian Carlstromaded5f72011-10-07 17:15:04 -07002125void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002126 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002127 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002128 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002129 if (IsDexFileRegisteredLocked(dex_file)) {
2130 return;
2131 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002132 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002133 // Don't alloc while holding the lock, since allocation may need to
2134 // suspend all threads and another thread may need the dex_lock_ to
2135 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002136 StackHandleScope<1> hs(self);
2137 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002138 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2139 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002140 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002141 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002142 if (IsDexFileRegisteredLocked(dex_file)) {
2143 return;
2144 }
2145 RegisterDexFileLocked(dex_file, dex_cache);
2146 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002147}
2148
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002149void ClassLinker::RegisterDexFile(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 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002152 RegisterDexFileLocked(dex_file, dex_cache);
2153}
2154
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002155mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002156 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002157 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002158 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002159 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002160 if (dex_cache->GetDexFile() == &dex_file) {
2161 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002162 }
2163 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002164 // Search matching by location name.
2165 std::string location(dex_file.GetLocation());
2166 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002167 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002168 if (dex_cache->GetDexFile()->GetLocation() == location) {
2169 return dex_cache;
2170 }
2171 }
2172 // Failure, dump diagnostic and abort.
2173 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002174 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002175 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2176 }
2177 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002178 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002179}
2180
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002181void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002182 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002183 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002184 mirror::DexCache* dex_cache = GetDexCache(i);
2185 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002186 }
2187}
2188
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002189mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002190 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002191 if (UNLIKELY(klass == nullptr)) {
2192 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002193 }
2194 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002195}
2196
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002197mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2198 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002199 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002200 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002201 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002202 StackHandleScope<1> hs(self);
2203 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002204 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002205 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2206 h_class->SetPrimitiveType(type);
2207 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002208 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002209 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002210 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002211 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002212 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07002213}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002214
Brian Carlstrombe977852011-07-19 14:54:54 -07002215// Create an array class (i.e. the class object for the array, not the
2216// array itself). "descriptor" looks like "[C" or "[[[[B" or
2217// "[Ljava/lang/String;".
2218//
2219// If "descriptor" refers to an array of primitives, look up the
2220// primitive type's internally-generated class object.
2221//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002222// "class_loader" is the class loader of the class that's referring to
2223// us. It's used to ensure that we're looking for the element type in
2224// the right context. It does NOT become the class loader for the
2225// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002226//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002227// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002228mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002229 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002230 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002231 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002232 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002233 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2234 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002235 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002236 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002237 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002238 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2239 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002240 if (component_type.Get() == nullptr) {
2241 DCHECK(self->IsExceptionPending());
2242 return nullptr;
2243 } else {
2244 self->ClearException();
2245 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002246 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002247 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2248 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2249 return nullptr;
2250 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002251 // See if the component type is already loaded. Array classes are
2252 // always associated with the class loader of their underlying
2253 // element type -- an array of Strings goes with the loader for
2254 // java/lang/String -- so we need to look for it there. (The
2255 // caller should have checked for the existence of the class
2256 // before calling here, but they did so with *their* class loader,
2257 // not the component type's loader.)
2258 //
2259 // If we find it, the caller adds "loader" to the class' initiating
2260 // loader list, which should prevent us from going through this again.
2261 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002262 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002263 // are the same, because our caller (FindClass) just did the
2264 // lookup. (Even if we get this wrong we still have correct behavior,
2265 // because we effectively do this lookup again when we add the new
2266 // class to the hash table --- necessary because of possible races with
2267 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002268 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002269 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002270 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002271 return new_class;
2272 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002273 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002274
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002275 // Fill out the fields in the Class.
2276 //
2277 // It is possible to execute some methods against arrays, because
2278 // all arrays are subclasses of java_lang_Object_, so we need to set
2279 // up a vtable. We can just point at the one in java_lang_Object_.
2280 //
2281 // Array classes are simple enough that we don't need to do a full
2282 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002283 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002284 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002285 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002286 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002287 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002288 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002289 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002290 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002291 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002292 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002293 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002294 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002295 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002296 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002297 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002298 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002299 } else if (strcmp(descriptor, "[J") == 0) {
2300 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002301 }
2302 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002303 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002304 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002305 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002306 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002307 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002308 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002309 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002310 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002311 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002312 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002313 new_class->SetSuperClass(java_lang_Object);
2314 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002315 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002316 new_class->SetClassLoader(component_type->GetClassLoader());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002317 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002318 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002319 StackHandleScope<mirror::Class::kImtSize> hs2(self,
2320 Runtime::Current()->GetImtUnimplementedMethod());
2321 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002322 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002323 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002324 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002325 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002326
2327
2328 // All arrays have java/lang/Cloneable and java/io/Serializable as
2329 // interfaces. We need to set that up here, so that stuff like
2330 // "instanceof" works right.
2331 //
2332 // Note: The GC could run during the call to FindSystemClass,
2333 // so we need to make sure the class object is GC-valid while we're in
2334 // there. Do this by clearing the interface list so the GC will just
2335 // think that the entries are null.
2336
2337
2338 // Use the single, global copies of "interfaces" and "iftable"
2339 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002340 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002341 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002342 CHECK(array_iftable != nullptr);
2343 new_class->SetIfTable(array_iftable);
2344 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002345
Elliott Hughes00626c22013-06-14 15:04:14 -07002346 // Inherit access flags from the component type.
2347 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2348 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2349 access_flags &= kAccJavaFlagsMask;
2350 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002351 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002352 access_flags |= kAccAbstract | kAccFinal;
2353 access_flags &= ~kAccInterface;
2354
2355 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002356
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002357 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002358 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002359 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002360 }
2361 // Another thread must have loaded the class after we
2362 // started but before we finished. Abandon what we've
2363 // done.
2364 //
2365 // (Yes, this happens.)
2366
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002367 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002368}
2369
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002370mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002371 switch (type) {
2372 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002373 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002374 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002375 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002376 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002377 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002378 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002379 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002380 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002381 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002382 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002383 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002384 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002385 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002386 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002387 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002388 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002389 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002390 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002391 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002392 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002393 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002394 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002395 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002396}
2397
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002398mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2399 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002400 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002401 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002402 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002403 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002404 source += " from ";
2405 source += dex_cache->GetLocation()->ToModifiedUtf8();
2406 }
2407 LOG(INFO) << "Loaded class " << descriptor << source;
2408 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002409 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002410 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002411 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002412 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002413 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002414 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002415 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002416 // Check a class loaded with the system class loader matches one in the image if the class
2417 // is in the image.
2418 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002419 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002420 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002421 }
2422 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002423 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002424 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002425 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002426 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002427 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002428 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002429}
2430
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002431mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2432 size_t hash) {
2433 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002434 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
2435 hash);
2436 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002437 CHECK(klass->IsProxyClass());
2438 return nullptr;
2439 }
2440
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002441 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002442 CHECK_NE(existing, klass) << descriptor;
2443 CHECK(!existing->IsResolved()) << descriptor;
2444 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2445
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002446 CHECK(!klass->IsTemp()) << descriptor;
2447 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2448 dex_cache_image_class_lookup_required_) {
2449 // Check a class loaded with the system class loader matches one in the image if the class
2450 // is in the image.
2451 existing = LookupClassFromImage(descriptor);
2452 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002453 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002454 }
2455 }
2456 VerifyObject(klass);
2457
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002458 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002459 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002460 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002461 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002462 }
2463
2464 return existing;
2465}
2466
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002467bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002468 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002469 auto pair = std::make_pair(descriptor, class_loader);
2470 auto it = class_table_.Find(pair);
2471 if (it != class_table_.end()) {
2472 class_table_.Erase(it);
2473 return true;
2474 }
2475 it = pre_zygote_class_table_.Find(pair);
2476 if (it != pre_zygote_class_table_.end()) {
2477 pre_zygote_class_table_.Erase(it);
2478 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08002479 }
2480 return false;
2481}
2482
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002483mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002484 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002485 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002486 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002487 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002488 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002489 return result;
2490 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002491 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002492 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2493 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002494 } else {
2495 // Lookup failed but need to search dex_caches_.
2496 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002497 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002498 InsertClass(descriptor, result, hash);
2499 } else {
2500 // Searching the image dex files/caches failed, we don't want to get into this situation
2501 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2502 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07002503 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002504 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2505 MoveImageClassesToClassTable();
2506 }
2507 }
2508 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002509 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002510}
2511
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002512mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002513 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002514 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002515 auto descriptor_pair = std::make_pair(descriptor, class_loader);
2516 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
2517 if (it == pre_zygote_class_table_.end()) {
2518 it = class_table_.FindWithHash(descriptor_pair, hash);
2519 if (it == class_table_.end()) {
2520 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07002521 }
2522 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002523 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002524}
2525
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002526static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2527 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2528 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002529 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002530 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2531 return root->AsObjectArray<mirror::DexCache>();
2532}
2533
2534void ClassLinker::MoveImageClassesToClassTable() {
2535 Thread* self = Thread::Current();
2536 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2537 if (!dex_cache_image_class_lookup_required_) {
2538 return; // All dex cache classes are already in the class table.
2539 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002540 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002541 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002542 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002543 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2544 mirror::DexCache* dex_cache = dex_caches->Get(i);
2545 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2546 for (int32_t j = 0; j < types->GetLength(); j++) {
2547 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002548 if (klass != nullptr) {
2549 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002550 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002551 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002552 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
2553 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002554 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002555 << PrettyClassAndClassLoader(klass);
2556 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002557 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002558 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002559 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002560 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002561 }
2562 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002563 }
2564 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002565 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002566}
2567
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002568void ClassLinker::MoveClassTableToPreZygote() {
2569 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2570 DCHECK(pre_zygote_class_table_.Empty());
2571 pre_zygote_class_table_ = std::move(class_table_);
2572 class_table_.Clear();
2573}
2574
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002575mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002576 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002577 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2578 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2579 mirror::DexCache* dex_cache = dex_caches->Get(i);
2580 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00002581 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002582 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002583 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002584 const DexFile::TypeId* type_id =
2585 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002586 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002587 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2588 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002589 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002590 return klass;
2591 }
2592 }
2593 }
2594 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002595 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002596}
2597
2598void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
2599 result.clear();
2600 if (dex_cache_image_class_lookup_required_) {
2601 MoveImageClassesToClassTable();
2602 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002603 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2604 while (true) {
2605 auto it = class_table_.Find(descriptor);
2606 if (it == class_table_.end()) {
2607 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002608 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002609 result.push_back(it->Read());
2610 class_table_.Erase(it);
2611 }
2612 for (mirror::Class* k : result) {
2613 class_table_.Insert(GcRoot<mirror::Class>(k));
2614 }
2615 size_t pre_zygote_start = result.size();
2616 // Now handle the pre zygote table.
2617 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
2618 // called from the debugger.
2619 while (true) {
2620 auto it = pre_zygote_class_table_.Find(descriptor);
2621 if (it == pre_zygote_class_table_.end()) {
2622 break;
2623 }
2624 result.push_back(it->Read());
2625 pre_zygote_class_table_.Erase(it);
2626 }
2627 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
2628 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002629 }
2630}
2631
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002632void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002633 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002634 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002635
Ian Rogers9ffb0392012-09-10 11:56:50 -07002636 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002637 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002638 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002639 return;
2640 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002641 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002642 return;
2643 }
jeffhao98eacac2011-09-14 16:11:53 -07002644
Ian Rogers9ffb0392012-09-10 11:56:50 -07002645 // The class might already be erroneous, for example at compile time if we attempted to verify
2646 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002647 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002648 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002649 return;
2650 }
2651
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002652 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002653 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002654 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002655 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002656 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002657 CHECK(!Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002658 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002659 }
jeffhao98eacac2011-09-14 16:11:53 -07002660
Jeff Hao4a200f52014-04-01 14:58:49 -07002661 // Skip verification if disabled.
2662 if (!Runtime::Current()->IsVerificationEnabled()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002663 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002664 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002665 return;
2666 }
2667
Ian Rogers9ffb0392012-09-10 11:56:50 -07002668 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002669 StackHandleScope<2> hs(self);
2670 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002671 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002672 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002673 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002674
2675 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002676 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002677 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002678 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002679 std::string error_msg(
2680 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2681 PrettyDescriptor(klass.Get()).c_str(),
2682 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002683 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002684 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002685 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002686 self->ClearException();
2687 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002688 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2689 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002690 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002691 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002692 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002693 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002694 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2695 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002696 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002697 return;
2698 }
2699 }
2700
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002701 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002702 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002703 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002704 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002705 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002706 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002707 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002708 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002709 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2710 PrettyDescriptor(klass.Get()).c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002711 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002712 return;
2713 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002714 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002715 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002716 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002717 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002718 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002719 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002720 }
2721 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002722 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002723 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002724 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2725 << " because: " << error_msg;
2726 }
Ian Rogers1f539342012-10-03 21:09:42 -07002727 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002728 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002729 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002730 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002731 // Even though there were no verifier failures we need to respect whether the super-class
2732 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002733 if (super.Get() == nullptr || super->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002734 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002735 } else {
2736 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002737 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002738 // Pretend a soft failure occured so that we don't consider the class verified below.
2739 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002740 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002741 } else {
2742 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2743 // Soft failures at compile time should be retried at runtime. Soft
2744 // failures at runtime will be handled by slow paths in the generated
2745 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002746 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002747 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002748 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002749 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002750 // As this is a fake verified status, make sure the methods are _not_ marked preverified
2751 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07002752 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002753 }
2754 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07002755 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08002756 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08002757 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2758 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002759 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002760 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002761 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07002762 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002763 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002764 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002765 // Let the interpreter know it by setting the kAccPreverified flag onto each
2766 // method.
2767 // Note: we're going here during compilation and at runtime. When we set the
2768 // kAccPreverified flag when compiling image classes, the flag is recorded
2769 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07002770 EnsurePreverifiedMethods(klass);
2771 }
2772}
2773
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002774void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002775 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002776 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07002777 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002778 }
jeffhao98eacac2011-09-14 16:11:53 -07002779}
2780
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002781bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
2782 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002783 // If we're compiling, we can only verify the class using the oat file if
2784 // we are not compiling the image or if the class we're verifying is not part of
2785 // the app. In other words, we will only check for preverification of bootclasspath
2786 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002787 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002788 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002789 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002790 return false;
2791 }
2792 // We are compiling an app (not the image).
2793
2794 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002795 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002796 return false;
2797 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002798 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002799
Richard Uhler07b3c232015-03-31 15:57:54 -07002800 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002801 // In case we run without an image there won't be a backing oat file.
2802 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07002803 return false;
2804 }
2805
Andreas Gampe76bd8802014-12-10 16:43:58 -08002806 // We may be running with a preopted oat file but without image. In this case,
2807 // we don't skip verification of preverified classes to ensure we initialize
2808 // dex caches with all types resolved during verification.
2809 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
2810 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
2811 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
2812 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002813 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08002814 !Runtime::Current()->GetHeap()->HasImageSpace() &&
2815 klass->GetClassLoader() != nullptr) {
2816 return false;
2817 }
2818
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002819 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002820 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002821 if (oat_file_class_status == mirror::Class::kStatusVerified ||
2822 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07002823 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002824 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002825 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07002826 // Compile time verification failed with a soft error. Compile time verification can fail
2827 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08002828 // class ... {
2829 // Foo x;
2830 // .... () {
2831 // if (...) {
2832 // v1 gets assigned a type of resolved class Foo
2833 // } else {
2834 // v1 gets assigned a type of unresolved class Bar
2835 // }
2836 // iput x = v1
2837 // } }
2838 // when we merge v1 following the if-the-else it results in Conflict
2839 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2840 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2841 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2842 // at compile time).
2843 return false;
2844 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002845 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07002846 // Compile time verification failed with a hard error. This is caused by invalid instructions
2847 // in the class. These errors are unrecoverable.
2848 return false;
2849 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002850 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08002851 // Status is uninitialized if we couldn't determine the status at compile time, for example,
2852 // not loading the class.
2853 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2854 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002855 return false;
2856 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07002857 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002858 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07002859 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07002860 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08002861 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002862}
2863
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002864void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002865 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002866 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2867 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2868 }
2869 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2870 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2871 }
2872}
2873
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002874void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07002875 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002876 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2877 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002878 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002879 return; // native or abstract method
2880 }
2881 if (code_item->tries_size_ == 0) {
2882 return; // nothing to process
2883 }
Ian Rogers13735952014-10-08 12:43:28 -07002884 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002885 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2886 ClassLinker* linker = Runtime::Current()->GetClassLinker();
2887 for (uint32_t idx = 0; idx < handlers_size; idx++) {
2888 CatchHandlerIterator iterator(handlers_ptr);
2889 for (; iterator.HasNext(); iterator.Next()) {
2890 // Ensure exception types are resolved so that they don't need resolution to be delivered,
2891 // unresolved exception types will be ignored by exception delivery
2892 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002893 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002894 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002895 DCHECK(Thread::Current()->IsExceptionPending());
2896 Thread::Current()->ClearException();
2897 }
2898 }
2899 }
2900 handlers_ptr = iterator.EndDataPointer();
2901 }
2902}
2903
Brian Carlstromea46f952013-07-30 01:26:50 -07002904static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002905static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
2906 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08002907
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002908mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07002909 jobjectArray interfaces, jobject loader,
2910 jobjectArray methods, jobjectArray throws) {
2911 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002912 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002913 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002914 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002915 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002916 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002917 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002918 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002919 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002920 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07002921 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
2922 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002923 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08002924 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002925 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002926 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002927 klass->SetDexCache(proxy_class->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002928 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08002929
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002930 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07002931 const size_t num_fields = 2;
2932 ArtField* sfields = AllocArtFieldArray(self, num_fields);
2933 klass->SetSFields(sfields);
2934 klass->SetNumStaticFields(num_fields);
2935
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002936 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2937 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002938 ArtField* interfaces_sfield = &sfields[0];
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002939 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002940 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002941 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002942
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002943 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002944 ArtField* throws_sfield = &sfields[1];
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002945 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002946 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07002947 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002948
Ian Rogers466bb252011-10-14 03:29:56 -07002949 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07002950 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002951 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002952 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002953 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002954 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002955 }
2956 klass->SetDirectMethods(directs);
2957 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002958 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002959 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002960 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002961 }
2962 klass->SetDirectMethod(0, constructor);
2963 }
Jesse Wilson95caa792011-10-12 18:14:17 -04002964
Mathieu Chartier590fee92013-09-13 13:46:47 -07002965 // Create virtual method using specified prototypes.
2966 size_t num_virtual_methods =
2967 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07002968 {
Brian Carlstromf3632832014-05-20 15:36:53 -07002969 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
2970 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002971 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002972 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002973 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002974 }
2975 klass->SetVirtualMethods(virtuals);
2976 }
Jesse Wilson95caa792011-10-12 18:14:17 -04002977 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002978 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002979 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
2980 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002981 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07002982 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002983 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002984 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002985 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002986 }
2987 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04002988 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002989
2990 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002991 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08002992 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08002993
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002994 std::string descriptor(GetDescriptorForProxy(klass.Get()));
2995 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07002996 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002997 // Must hold lock on object when resolved.
2998 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002999 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003000 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003001 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003002 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003003 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003004 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003005 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003006 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003007
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003008 CHECK(klass->IsRetired());
3009 CHECK_NE(klass.Get(), new_class);
3010 klass.Assign(new_class);
3011
3012 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003013 interfaces_sfield->SetObject<false>(klass.Get(),
3014 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003015 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003016 throws_sfield->SetObject<false>(klass.Get(),
3017 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003018
3019 {
3020 // Lock on klass is released. Lock new class object.
3021 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003022 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003023 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003024
3025 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003026 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003027 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003028 CheckProxyConstructor(klass->GetDirectMethod(0));
3029 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003030 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003031 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3032 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003033 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3034 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003035 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003036 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003037
Mathieu Chartier590fee92013-09-13 13:46:47 -07003038 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003039 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003040 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003041 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3042
3043 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003044 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003045 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003046
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003047 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003048 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003049 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003050 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003051 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003052 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3053 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003054 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003055 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003056}
3057
Ian Rogersef7d42f2014-01-06 12:55:46 -08003058std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003059 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003060 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003061 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003062 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3063}
3064
Ian Rogersef7d42f2014-01-06 12:55:46 -08003065mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3066 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003067 DCHECK(proxy_class->IsProxyClass());
3068 DCHECK(proxy_method->IsProxyMethod());
3069 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003070 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003071 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003072 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003073 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003074 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003075 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003076 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003077 break;
3078 }
3079 }
3080 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003081 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003082 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003083 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003084 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003085 return resolved_method;
3086}
3087
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003088
Brian Carlstromea46f952013-07-30 01:26:50 -07003089mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003090 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003091 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003092 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003093 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003094 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003095 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3096 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003097 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3098 // constructor method.
3099 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3100 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003101 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3102 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003103 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3104 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003105 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003106 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003107 }
Ian Rogers466bb252011-10-14 03:29:56 -07003108 // Make this constructor public and fix the class to be our Proxy version
3109 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003110 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003111 return constructor;
3112}
3113
Brian Carlstromea46f952013-07-30 01:26:50 -07003114static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003115 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003116 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003117 CHECK_STREQ(constructor->GetName(), "<init>");
3118 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3119 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003120 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003121}
3122
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003123mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003124 Handle<mirror::Class> klass,
3125 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003126 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3127 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08003128 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003129 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003130 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003131 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003132 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003133 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003134 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003135 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003136 }
Ian Rogers466bb252011-10-14 03:29:56 -07003137
3138 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3139 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003140 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003141 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003142
Ian Rogers466bb252011-10-14 03:29:56 -07003143 // At runtime the method looks like a reference and argument saving method, clone the code
3144 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003145 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003146 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003147
Ian Rogersc2b44472011-12-14 21:17:17 -08003148 return method;
3149}
Jesse Wilson95caa792011-10-12 18:14:17 -04003150
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003151static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3152 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003153 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003154 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003155 CHECK(!prototype->IsFinal());
3156 CHECK(method->IsFinal());
3157 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003158
3159 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3160 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07003161 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3162 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08003163 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3164
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003165 CHECK_STREQ(method->GetName(), prototype->GetName());
3166 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003167 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07003168 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003169}
3170
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003171static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3172 bool can_init_parents)
3173 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003174 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003175 return true;
3176 }
3177 if (!can_init_statics) {
3178 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003179 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003180 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003181 return false;
3182 }
3183 // Check if there are encoded static values needing initialization.
3184 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003185 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003186 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003187 if (dex_class_def->static_values_off_ != 0) {
3188 return false;
3189 }
3190 }
3191 }
3192 if (!klass->IsInterface() && klass->HasSuperClass()) {
3193 mirror::Class* super_class = klass->GetSuperClass();
3194 if (!can_init_parents && !super_class->IsInitialized()) {
3195 return false;
3196 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003197 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003198 return false;
3199 }
3200 }
3201 }
3202 return true;
3203}
3204
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003205bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07003206 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003207 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3208
3209 // Are we already initialized and therefore done?
3210 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3211 // an initialized class will never change its state.
3212 if (klass->IsInitialized()) {
3213 return true;
3214 }
3215
3216 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003217 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003218 return false;
3219 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003220
Ian Rogers7b078e82014-09-10 14:44:24 -07003221 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003222 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003223 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003224 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003225
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003226 // Re-check under the lock in case another thread initialized ahead of us.
3227 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003228 return true;
3229 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003230
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003231 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003232 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003233 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003234 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003235 return false;
3236 }
3237
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003238 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003239
3240 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003241 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003242 if (!klass->IsVerified()) {
3243 // We failed to verify, expect either the klass to be erroneous or verification failed at
3244 // compile time.
3245 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003246 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003247 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003248 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003249 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003250 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003251 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003252 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003253 } else {
3254 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003255 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003256 }
3257
Brian Carlstromd1422f82011-09-28 11:37:09 -07003258 // If the class is kStatusInitializing, either this thread is
3259 // initializing higher up the stack or another thread has beat us
3260 // to initializing and we need to wait. Either way, this
3261 // invocation of InitializeClass will not be responsible for
3262 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003263 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003264 // Could have got an exception during verification.
3265 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003266 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003267 return false;
3268 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003269 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003270 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003271 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003272 return true;
3273 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003274 // No. That's fine. Wait for another thread to finish initializing.
3275 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003276 }
3277
3278 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003279 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003280 return false;
3281 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003282 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003283
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003284 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003285
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003286 // From here out other threads may observe that we're initializing and so changes of state
3287 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003288 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003289 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003290
3291 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003292 }
3293
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003294 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003295 if (!klass->IsInterface() && klass->HasSuperClass()) {
3296 mirror::Class* super_class = klass->GetSuperClass();
3297 if (!super_class->IsInitialized()) {
3298 CHECK(!super_class->IsInterface());
3299 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003300 StackHandleScope<1> hs(self);
3301 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003302 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003303 if (!super_initialized) {
3304 // The super class was verified ahead of entering initializing, we should only be here if
3305 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003306 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003307 << "Super class initialization failed for "
3308 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003309 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003310 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003311 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003312 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003313 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003314 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003315 return false;
3316 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003317 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003318 }
3319
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003320 const size_t num_static_fields = klass->NumStaticFields();
3321 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003322 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003323 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003324 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003325 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003326 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003327 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003328
3329 // Eagerly fill in static fields so that the we don't have to do as many expensive
3330 // Class::FindStaticField in ResolveField.
3331 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003332 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003333 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003334 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003335 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003336 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003337 } else {
3338 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003339 }
3340 }
3341
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003342 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3343 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003344 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003345 ClassDataItemIterator field_it(dex_file, class_data);
3346 if (value_it.HasNext()) {
3347 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003348 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003349 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003350 ArtField* field = ResolveField(
3351 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003352 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003353 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003354 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003355 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003356 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003357 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003358 }
3359 }
3360 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003361
Ian Rogersd91d6d62013-09-25 20:26:14 -07003362 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003363 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003364 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003365 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003366 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003367 }
3368
Ian Rogers7b078e82014-09-10 14:44:24 -07003369 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003370 uint64_t t1 = NanoTime();
3371
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003372 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003373 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003374 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003375
3376 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003377 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003378 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003379 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003380 } else if (Runtime::Current()->IsTransactionAborted()) {
3381 // The exception thrown when the transaction aborted has been caught and cleared
3382 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003383 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3384 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02003385 Runtime::Current()->ThrowTransactionAbortError(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003386 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003387 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003388 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003389 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3390 RuntimeStats* thread_stats = self->GetStats();
3391 ++global_stats->class_init_count;
3392 ++thread_stats->class_init_count;
3393 global_stats->class_init_time_ns += (t1 - t0);
3394 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003395 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003396 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003397 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003398 std::string temp;
3399 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003400 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003401 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003402 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003403 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003404 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003405 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003406 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003407}
3408
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003409bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003410 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003411 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003412 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003413 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003414 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003415 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003416
3417 // When we wake up, repeat the test for init-in-progress. If
3418 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003419 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003420 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003421 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003422 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003423 return false;
3424 }
3425 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003426 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003427 continue;
3428 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003429 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3430 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003431 // Compile time initialization failed.
3432 return false;
3433 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003434 if (klass->IsErroneous()) {
3435 // The caller wants an exception, but it was thrown in a
3436 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003437 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003438 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003439 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003440 return false;
3441 }
3442 if (klass->IsInitialized()) {
3443 return true;
3444 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003445 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003446 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003447 }
Ian Rogers07140832014-09-30 15:43:59 -07003448 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003449}
3450
Ian Rogersb5fb2072014-12-02 17:22:02 -08003451static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
3452 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003453 Handle<mirror::ArtMethod> method2,
3454 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08003455 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3456 {
3457 StackHandleScope<1> hs(self);
3458 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00003459 mirror::Class* other_return_type = method2->GetReturnType();
3460 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
3461 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003462 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3463 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3464 return_type.Get(),
3465 PrettyClassAndClassLoader(other_return_type).c_str(),
3466 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003467 return false;
3468 }
3469 }
3470 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3471 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3472 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003473 if (types2 != nullptr && types2->Size() != 0) {
3474 *error_msg = StringPrintf("Type list mismatch with %s",
3475 PrettyMethod(method2.Get(), true).c_str());
3476 return false;
3477 }
3478 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003479 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003480 if (types1->Size() != 0) {
3481 *error_msg = StringPrintf("Type list mismatch with %s",
3482 PrettyMethod(method2.Get(), true).c_str());
3483 return false;
3484 }
3485 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003486 }
3487 uint32_t num_types = types1->Size();
3488 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003489 *error_msg = StringPrintf("Type list mismatch with %s",
3490 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08003491 return false;
3492 }
3493 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003494 StackHandleScope<1> hs(self);
3495 Handle<mirror::Class> param_type(hs.NewHandle(
3496 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003497 mirror::Class* other_param_type =
3498 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00003499 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
3500 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003501 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3502 i,
3503 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3504 param_type.Get(),
3505 PrettyClassAndClassLoader(other_param_type).c_str(),
3506 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003507 return false;
3508 }
3509 }
3510 return true;
3511}
3512
3513
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003514bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003515 if (klass->IsInterface()) {
3516 return true;
3517 }
Ian Rogers151f2212014-05-06 11:27:27 -07003518 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003519 Thread* self = Thread::Current();
3520 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003521 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
3522 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003523 if (klass->HasSuperClass() &&
3524 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003525 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003526 h_m.Assign(klass->GetVTableEntry(i));
3527 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003528 if (h_m.Get() != super_h_m.Get()) {
3529 std::string error_msg;
3530 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3531 ThrowLinkageError(klass.Get(),
3532 "Class %s method %s resolves differently in superclass %s: %s",
3533 PrettyDescriptor(klass.Get()).c_str(),
3534 PrettyMethod(h_m.Get()).c_str(),
3535 PrettyDescriptor(klass->GetSuperClass()).c_str(),
3536 error_msg.c_str());
3537 return false;
3538 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003539 }
3540 }
3541 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003542 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003543 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3544 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3545 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003546 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3547 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003548 if (h_m.Get() != super_h_m.Get()) {
3549 std::string error_msg;
3550 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3551 ThrowLinkageError(klass.Get(),
3552 "Class %s method %s resolves differently in interface %s: %s",
3553 PrettyDescriptor(klass.Get()).c_str(),
3554 PrettyMethod(h_m.Get()).c_str(),
3555 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
3556 error_msg.c_str());
3557 return false;
3558 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003559 }
3560 }
3561 }
3562 }
3563 return true;
3564}
3565
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003566bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
3567 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003568 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003569 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003570 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003571 return true;
3572 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003573 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003574 if (!success) {
3575 if (can_init_fields && can_init_parents) {
3576 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3577 }
3578 } else {
3579 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003580 }
3581 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003582}
3583
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003584void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003585 ArtField* fields = new_class->GetIFields();
3586 for (size_t i = 0, count = new_class->NumInstanceFields(); i < count; i++) {
3587 if (fields[i].GetDeclaringClass() == temp_class) {
3588 fields[i].SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003589 }
3590 }
3591
3592 fields = new_class->GetSFields();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003593 for (size_t i = 0, count = new_class->NumStaticFields(); i < count; i++) {
3594 if (fields[i].GetDeclaringClass() == temp_class) {
3595 fields[i].SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003596 }
3597 }
3598
3599 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3600 if (methods != nullptr) {
3601 for (int index = 0; index < methods->GetLength(); index ++) {
3602 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3603 methods->Get(index)->SetDeclaringClass(new_class);
3604 }
3605 }
3606 }
3607
3608 methods = new_class->GetVirtualMethods();
3609 if (methods != nullptr) {
3610 for (int index = 0; index < methods->GetLength(); index ++) {
3611 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3612 methods->Get(index)->SetDeclaringClass(new_class);
3613 }
3614 }
3615 }
3616}
3617
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003618bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3619 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003620 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003621 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003622
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003623 if (!LinkSuperClass(klass)) {
3624 return false;
3625 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003626 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
3627 self, Runtime::Current()->GetImtUnimplementedMethod());
3628 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003629 return false;
3630 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003631 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003632 return false;
3633 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003634 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07003635 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003636 return false;
3637 }
3638 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003639 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003640
3641 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3642 // We don't need to retire this class as it has no embedded tables or it was created the
3643 // correct size during class linker initialization.
3644 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3645
3646 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003647 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003648 }
3649
3650 // This will notify waiters on klass that saw the not yet resolved
3651 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003652 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003653 *new_class = klass.Get();
3654 } else {
3655 CHECK(!klass->IsResolved());
3656 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003657 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003658 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003659 CHECK(self->IsExceptionPending()); // Expect an OOME.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003660 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003661 return false;
3662 }
3663
3664 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3665 StackHandleScope<1> hs(self);
3666 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3667 ObjectLock<mirror::Class> lock(self, new_class_h);
3668
3669 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
3670
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003671 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
3672 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003673 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003674
3675 // This will notify waiters on temp class that saw the not yet resolved class in the
3676 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003677 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003678
3679 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
3680 // This will notify waiters on new_class that saw the not yet resolved
3681 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003682 mirror::Class::SetStatus(new_class_h, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003683 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003684 return true;
3685}
3686
Andreas Gampefd9eb392014-11-06 16:52:58 -08003687static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
3688 size_t* virtual_methods,
3689 size_t* direct_methods,
3690 size_t* static_fields,
3691 size_t* instance_fields) {
3692 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
3693
3694 while (dex_data.HasNextStaticField()) {
3695 dex_data.Next();
3696 (*static_fields)++;
3697 }
3698 while (dex_data.HasNextInstanceField()) {
3699 dex_data.Next();
3700 (*instance_fields)++;
3701 }
3702 while (dex_data.HasNextDirectMethod()) {
3703 (*direct_methods)++;
3704 dex_data.Next();
3705 }
3706 while (dex_data.HasNextVirtualMethod()) {
3707 (*virtual_methods)++;
3708 dex_data.Next();
3709 }
3710 DCHECK(!dex_data.HasNext());
3711}
3712
3713static void DumpClass(std::ostream& os,
3714 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
3715 const char* suffix) {
3716 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
3717 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
3718 os << " Static fields:\n";
3719 while (dex_data.HasNextStaticField()) {
3720 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3721 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3722 dex_data.Next();
3723 }
3724 os << " Instance fields:\n";
3725 while (dex_data.HasNextInstanceField()) {
3726 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3727 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3728 dex_data.Next();
3729 }
3730 os << " Direct methods:\n";
3731 while (dex_data.HasNextDirectMethod()) {
3732 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3733 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3734 dex_data.Next();
3735 }
3736 os << " Virtual methods:\n";
3737 while (dex_data.HasNextVirtualMethod()) {
3738 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3739 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3740 dex_data.Next();
3741 }
3742}
3743
3744static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3745 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
3746 std::ostringstream os;
3747 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
3748 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
3749 return os.str();
3750}
3751
3752
3753// Very simple structural check on whether the classes match. Only compares the number of
3754// methods and fields.
3755static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
3756 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
3757 std::string* error_msg) {
3758 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
3759 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
3760
3761 // Counters for current dex file.
3762 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
3763 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
3764 &dex_instance_fields1);
3765 // Counters for compile-time dex file.
3766 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
3767 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
3768 &dex_instance_fields2);
3769
3770 if (dex_virtual_methods1 != dex_virtual_methods2) {
3771 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3772 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
3773 dex_virtual_methods2, class_dump.c_str());
3774 return false;
3775 }
3776 if (dex_direct_methods1 != dex_direct_methods2) {
3777 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3778 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
3779 dex_direct_methods2, class_dump.c_str());
3780 return false;
3781 }
3782 if (dex_static_fields1 != dex_static_fields2) {
3783 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3784 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
3785 dex_static_fields2, class_dump.c_str());
3786 return false;
3787 }
3788 if (dex_instance_fields1 != dex_instance_fields2) {
3789 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
3790 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
3791 dex_instance_fields2, class_dump.c_str());
3792 return false;
3793 }
3794
3795 return true;
3796}
3797
3798// Checks whether a the super-class changed from what we had at compile-time. This would
3799// invalidate quickening.
3800static bool CheckSuperClassChange(Handle<mirror::Class> klass,
3801 const DexFile& dex_file,
3802 const DexFile::ClassDef& class_def,
3803 mirror::Class* super_class)
3804 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3805 // Check for unexpected changes in the superclass.
3806 // Quick check 1) is the super_class class-loader the boot class loader? This always has
3807 // precedence.
3808 if (super_class->GetClassLoader() != nullptr &&
3809 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
3810 // which is implied by different dex cache.
3811 klass->GetDexCache() != super_class->GetDexCache()) {
3812 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
3813 // definition for the super-class, and (b) the files are in separate oat files. The oat files
3814 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07003815 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
3816 const OatFile* class_oat_file = nullptr;
3817 if (class_oat_dex_file != nullptr) {
3818 class_oat_file = class_oat_dex_file->GetOatFile();
3819 }
3820
Andreas Gampefd9eb392014-11-06 16:52:58 -08003821 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07003822 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
3823 const OatFile* loaded_super_oat_file = nullptr;
3824 if (loaded_super_oat_dex_file != nullptr) {
3825 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
3826 }
3827
Andreas Gampefd9eb392014-11-06 16:52:58 -08003828 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
3829 // Now check (a).
3830 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
3831 if (super_class_def != nullptr) {
3832 // Uh-oh, we found something. Do our check.
3833 std::string error_msg;
3834 if (!SimpleStructuralCheck(dex_file, *super_class_def,
3835 super_class->GetDexFile(), *super_class->GetClassDef(),
3836 &error_msg)) {
3837 // Print a warning to the log. This exception might be caught, e.g., as common in test
3838 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
3839 // only save the type of the exception.
3840 LOG(WARNING) << "Incompatible structural change detected: " <<
3841 StringPrintf(
3842 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3843 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3844 class_oat_file->GetLocation().c_str(),
3845 loaded_super_oat_file->GetLocation().c_str(),
3846 error_msg.c_str());
3847 ThrowIncompatibleClassChangeError(klass.Get(),
3848 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
3849 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
3850 class_oat_file->GetLocation().c_str(),
3851 loaded_super_oat_file->GetLocation().c_str(),
3852 error_msg.c_str());
3853 return false;
3854 }
3855 }
3856 }
3857 }
3858 }
3859 return true;
3860}
3861
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003862bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003863 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003864 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3865 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003866 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003867 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003868 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07003869 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003870 return false;
3871 }
Ian Rogersbe125a92012-01-11 15:19:49 -08003872 // Verify
3873 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003874 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003875 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003876 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08003877 return false;
3878 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003879 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003880 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08003881
3882 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
3883 DCHECK(Thread::Current()->IsExceptionPending());
3884 return false;
3885 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003886 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003887 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003888 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003889 for (size_t i = 0; i < interfaces->Size(); i++) {
3890 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003891 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003892 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003893 DCHECK(Thread::Current()->IsExceptionPending());
3894 return false;
3895 }
3896 // Verify
3897 if (!klass->CanAccess(interface)) {
3898 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003899 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08003900 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003901 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003902 return false;
3903 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003904 }
3905 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003906 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003907 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003908 return true;
3909}
3910
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003911bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003912 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003913 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003914 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003915 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003916 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003917 return false;
3918 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003919 return true;
3920 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003921 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003922 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
3923 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003924 return false;
3925 }
3926 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003927 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003928 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003929 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003930 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003931 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003932 return false;
3933 }
3934 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003935 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08003936 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003937 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003938 return false;
3939 }
Elliott Hughes20cde902011-10-04 17:37:27 -07003940
Brian Carlstromf3632832014-05-20 15:36:53 -07003941 // Inherit kAccClassIsFinalizable from the superclass in case this
3942 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07003943 if (super->IsFinalizable()) {
3944 klass->SetFinalizable();
3945 }
3946
Elliott Hughes2da50362011-10-10 16:57:08 -07003947 // Inherit reference flags (if any) from the superclass.
3948 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
3949 if (reference_flags != 0) {
3950 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
3951 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003952 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07003953 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003954 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08003955 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003956 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07003957 return false;
3958 }
Elliott Hughes2da50362011-10-10 16:57:08 -07003959
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003960 if (kIsDebugBuild) {
3961 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003962 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003963 CHECK(super->IsResolved());
3964 super = super->GetSuperClass();
3965 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003966 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003967 return true;
3968}
3969
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003970// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003971bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003972 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
3973 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003974 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003975 if (klass->IsInterface()) {
3976 // No vtable.
3977 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08003978 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003979 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003980 return false;
3981 }
Carl Shapiro565f5072011-07-10 13:39:43 -07003982 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003983 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003984 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003985 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
3986 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003987 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003988 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003989}
3990
Ian Rogers03b6eaf2014-10-28 09:34:57 -07003991// Comparator for name and signature of a method, used in finding overriding methods. Implementation
3992// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
3993// caches in the implementation below.
3994class MethodNameAndSignatureComparator FINAL : public ValueObject {
3995 public:
3996 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
3997 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
3998 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
3999 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004000 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4001 }
4002
4003 const char* GetName() {
4004 if (name_ == nullptr) {
4005 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4006 }
4007 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004008 }
4009
4010 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4011 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4012 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4013 const DexFile* other_dex_file = other->GetDexFile();
4014 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4015 if (dex_file_ == other_dex_file) {
4016 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4017 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004018 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004019 uint32_t other_name_len;
4020 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4021 &other_name_len);
4022 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4023 return false;
4024 }
4025 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4026 }
4027
4028 private:
4029 // Dex file for the method to compare against.
4030 const DexFile* const dex_file_;
4031 // MethodId for the method to compare against.
4032 const DexFile::MethodId* const mid_;
4033 // Lazily computed name from the dex file's strings.
4034 const char* name_;
4035 // Lazily computed name length.
4036 uint32_t name_len_;
4037};
4038
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004039class LinkVirtualHashTable {
4040 public:
4041 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4042 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4043 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4044 }
4045 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4046 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4047 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004048 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004049 uint32_t index = hash % hash_size_;
4050 // Linear probe until we have an empty slot.
4051 while (hash_table_[index] != invalid_index_) {
4052 if (++index == hash_size_) {
4053 index = 0;
4054 }
4055 }
4056 hash_table_[index] = virtual_method_index;
4057 }
4058 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4059 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4060 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004061 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004062 size_t index = hash % hash_size_;
4063 while (true) {
4064 const uint32_t value = hash_table_[index];
4065 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4066 // the block and can safely assume not found.
4067 if (value == invalid_index_) {
4068 break;
4069 }
4070 if (value != removed_index_) { // This signifies not already overriden.
4071 mirror::ArtMethod* virtual_method =
4072 klass_->GetVirtualMethodDuringLinking(value);
4073 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4074 hash_table_[index] = removed_index_;
4075 return value;
4076 }
4077 }
4078 if (++index == hash_size_) {
4079 index = 0;
4080 }
4081 }
4082 return GetNotFoundIndex();
4083 }
4084 static uint32_t GetNotFoundIndex() {
4085 return invalid_index_;
4086 }
4087
4088 private:
4089 static const uint32_t invalid_index_;
4090 static const uint32_t removed_index_;
4091
4092 Handle<mirror::Class> klass_;
4093 const size_t hash_size_;
4094 uint32_t* const hash_table_;
4095};
4096
4097const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4098const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4099
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004100bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004101 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004102 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004103 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4104 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004105 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004106 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004107 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004108 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4109 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4110 if (UNLIKELY(vtable.Get() == nullptr)) {
4111 CHECK(self->IsExceptionPending()); // OOME.
4112 return false;
4113 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004114 for (size_t i = 0; i < super_vtable_length; i++) {
4115 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004116 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004117 if (num_virtual_methods == 0) {
4118 klass->SetVTable(vtable.Get());
4119 return true;
4120 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004121 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004122 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4123 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4124 if (num_virtual_methods == 0) {
4125 klass->SetVTable(super_vtable);
4126 return true;
4127 }
4128 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004129 if (UNLIKELY(vtable.Get() == nullptr)) {
4130 CHECK(self->IsExceptionPending()); // OOME.
4131 return false;
4132 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004133 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004134 // How the algorithm works:
4135 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4136 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4137 // method which has not been matched to a vtable method, and j if the virtual method at the
4138 // index overrode the super virtual method at index j.
4139 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4140 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4141 // the need for the initial vtable which we later shrink back down).
4142 // 3. Add non overridden methods to the end of the vtable.
4143 static constexpr size_t kMaxStackHash = 250;
4144 const size_t hash_table_size = num_virtual_methods * 3;
4145 uint32_t* hash_table_ptr;
4146 std::unique_ptr<uint32_t[]> hash_heap_storage;
4147 if (hash_table_size <= kMaxStackHash) {
4148 hash_table_ptr = reinterpret_cast<uint32_t*>(
4149 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4150 } else {
4151 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4152 hash_table_ptr = hash_heap_storage.get();
4153 }
4154 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4155 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004156 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004157 hash_table.Add(i);
4158 }
4159 // Loop through each super vtable method and see if they are overriden by a method we added to
4160 // the hash table.
4161 for (size_t j = 0; j < super_vtable_length; ++j) {
4162 // Search the hash table to see if we are overidden by any method.
4163 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4164 MethodNameAndSignatureComparator super_method_name_comparator(
4165 super_method->GetInterfaceMethodIfProxy());
4166 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4167 if (hash_index != hash_table.GetNotFoundIndex()) {
4168 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4169 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4170 super_method->GetAccessFlags())) {
4171 if (super_method->IsFinal()) {
4172 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4173 PrettyMethod(virtual_method).c_str(),
4174 super_method->GetDeclaringClassDescriptor());
4175 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004176 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004177 vtable->SetWithoutChecks<false>(j, virtual_method);
4178 virtual_method->SetMethodIndex(j);
4179 } else {
4180 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004181 << " would have incorrectly overridden the package-private method in "
4182 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004183 }
4184 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004185 }
4186 // Add the non overridden methods at the end.
4187 size_t actual_count = super_vtable_length;
4188 for (size_t i = 0; i < num_virtual_methods; ++i) {
4189 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4190 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4191 if (method_idx < super_vtable_length &&
4192 local_method == vtable->GetWithoutChecks(method_idx)) {
4193 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004194 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004195 vtable->SetWithoutChecks<false>(actual_count, local_method);
4196 local_method->SetMethodIndex(actual_count);
4197 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004198 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004199 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004200 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004201 return false;
4202 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004203 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004204 CHECK_LE(actual_count, max_count);
4205 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004206 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004207 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004208 CHECK(self->IsExceptionPending()); // OOME.
4209 return false;
4210 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004211 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004212 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004213 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004214 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004215 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004216 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4217 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004218 return false;
4219 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004220 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4221 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004222 CHECK(self->IsExceptionPending()); // OOME.
4223 return false;
4224 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004225 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004226 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004227 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004228 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004229 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004230 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004231 }
4232 return true;
4233}
4234
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004235bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4236 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4237 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004238 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004239 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004240 const bool has_superclass = klass->HasSuperClass();
4241 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4242 const bool have_interfaces = interfaces.Get() != nullptr;
4243 const size_t num_interfaces =
4244 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4245 if (num_interfaces == 0) {
4246 if (super_ifcount == 0) {
4247 // Class implements no interfaces.
4248 DCHECK_EQ(klass->GetIfTableCount(), 0);
4249 DCHECK(klass->GetIfTable() == nullptr);
4250 return true;
4251 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004252 // Class implements same interfaces as parent, are any of these not marker interfaces?
4253 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004254 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004255 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004256 if (super_iftable->GetMethodArrayCount(i) > 0) {
4257 has_non_marker_interface = true;
4258 break;
4259 }
4260 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004261 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004262 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004263 klass->SetIfTable(super_iftable);
4264 return true;
4265 }
4266 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004267 size_t ifcount = super_ifcount + num_interfaces;
4268 for (size_t i = 0; i < num_interfaces; i++) {
4269 mirror::Class* interface = have_interfaces ?
4270 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4271 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004272 if (UNLIKELY(!interface->IsInterface())) {
4273 std::string temp;
4274 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4275 PrettyDescriptor(klass.Get()).c_str(),
4276 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4277 return false;
4278 }
4279 ifcount += interface->GetIfTableCount();
4280 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004281 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004282 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004283 CHECK(self->IsExceptionPending()); // OOME.
4284 return false;
4285 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004286 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004287 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004288 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004289 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004290 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004291 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004292 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004293 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004294 // Flatten the interface inheritance hierarchy.
4295 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004296 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004297 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4298 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004299 // Check if interface is already in iftable
4300 bool duplicate = false;
4301 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004302 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004303 if (existing_interface == interface) {
4304 duplicate = true;
4305 break;
4306 }
4307 }
4308 if (!duplicate) {
4309 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004310 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004311 // Add this interface's non-duplicate super-interfaces.
4312 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004313 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004314 bool super_duplicate = false;
4315 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004316 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004317 if (existing_interface == super_interface) {
4318 super_duplicate = true;
4319 break;
4320 }
4321 }
4322 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004323 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004324 }
4325 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004326 }
4327 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004328 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004329 // Shrink iftable in case duplicates were found
4330 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004331 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004332 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004333 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004334 CHECK(self->IsExceptionPending()); // OOME.
4335 return false;
4336 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004337 ifcount = idx;
4338 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004339 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004340 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004341 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004342 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004343 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004344 return true;
4345 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004346 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004347 size_t max_miranda_methods = 0; // The max size of miranda_list.
4348 for (size_t i = 0; i < ifcount; ++i) {
4349 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4350 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004351 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004352 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004353 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4354 hs.NewHandle(klass->GetVTableDuringLinking()));
4355 // Copy the IMT from the super class if possible.
4356 bool extend_super_iftable = false;
4357 if (has_superclass) {
4358 mirror::Class* super_class = klass->GetSuperClass();
4359 extend_super_iftable = true;
4360 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4361 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4362 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4363 }
4364 } else {
4365 // No imt in the super class, need to reconstruct from the iftable.
4366 mirror::IfTable* if_table = super_class->GetIfTable();
4367 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4368 const size_t length = super_class->GetIfTableCount();
4369 for (size_t i = 0; i < length; ++i) {
4370 mirror::Class* interface = iftable->GetInterface(i);
4371 const size_t num_virtuals = interface->NumVirtualMethods();
4372 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4373 DCHECK_EQ(num_virtuals, method_array_count);
4374 if (method_array_count == 0) {
4375 continue;
4376 }
4377 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4378 for (size_t j = 0; j < num_virtuals; ++j) {
4379 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4380 if (method->IsMiranda()) {
4381 continue;
4382 }
4383 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4384 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4385 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4386 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4387 out_imt->SetReference(imt_index, method);
4388 } else if (imt_ref != conflict_method) {
4389 out_imt->SetReference(imt_index, conflict_method);
4390 }
4391 }
4392 }
4393 }
4394 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004395 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004396 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004397 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004398 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004399 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004400 const bool is_super = i < super_ifcount;
4401 const bool super_interface = is_super && extend_super_iftable;
4402 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4403 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4404 if (super_interface) {
4405 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4406 DCHECK(if_table != nullptr);
4407 DCHECK(if_table->GetMethodArray(i) != nullptr);
4408 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004409 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004410 AsObjectArray<mirror::ArtMethod>());
4411 // We are overwriting a super class interface, try to only virtual methods instead of the
4412 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004413 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004414 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004415 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004416 // A new interface, we need the whole vtable incase a new interface method is implemented
4417 // in the whole superclass.
4418 input_array = vtable;
4419 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004420 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004421 CHECK(self->IsExceptionPending()); // OOME.
4422 return false;
4423 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004424 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004425 if (input_array.Get() == nullptr) {
4426 // If the added virtual methods is empty, do nothing.
4427 DCHECK(super_interface);
4428 continue;
4429 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004430 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004431 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004432 MethodNameAndSignatureComparator interface_name_comparator(
4433 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07004434 int32_t k;
4435 // For each method listed in the interface's method list, find the
4436 // matching method in our class's method list. We want to favor the
4437 // subclass over the superclass, which just requires walking
4438 // back from the end of the vtable. (This only matters if the
4439 // superclass defines a private method and this class redefines
4440 // it -- otherwise it would use the same vtable slot. In .dex files
4441 // those don't end up in the virtual method table, so it shouldn't
4442 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004443 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4444 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004445 mirror::ArtMethod* vtable_method_for_name_comparison =
4446 vtable_method->GetInterfaceMethodIfProxy();
4447 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004448 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004449 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004450 ThrowIllegalAccessError(
4451 klass.Get(),
4452 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004453 PrettyMethod(vtable_method).c_str(),
4454 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004455 return false;
4456 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004457 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004458 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004459 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4460 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4461 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4462 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4463 out_imt->SetReference(imt_index, vtable_method);
4464 } else if (imt_ref != conflict_method) {
4465 // If we are not a conflict and we have the same signature and name as the imt entry,
4466 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004467 MethodNameAndSignatureComparator imt_ref_name_comparator(
4468 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004469 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004470 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004471 out_imt->SetReference(imt_index, vtable_method);
4472 } else {
4473 out_imt->SetReference(imt_index, conflict_method);
4474 }
Jeff Hao88474b42013-10-23 16:24:40 -07004475 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004476 break;
4477 }
4478 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004479 if (k < 0 && !super_interface) {
4480 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004481 for (size_t l = 0; l < miranda_list_size; ++l) {
4482 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004483 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004484 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07004485 break;
4486 }
4487 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004488 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004489 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004490 miranda_method = interface_method->Clone(self)->AsArtMethod();
4491 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004492 CHECK(self->IsExceptionPending()); // OOME.
4493 return false;
4494 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004495 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004496 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004497 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004498 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004499 }
4500 }
4501 }
4502 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004503 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004504 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004505 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004506 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4507 if (old_method_count == 0) {
4508 virtuals = AllocArtMethodArray(self, new_method_count);
4509 } else {
4510 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4511 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004512 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004513 CHECK(self->IsExceptionPending()); // OOME.
4514 return false;
4515 }
4516 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004517
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004518 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004519 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004520 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004521 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004522 CHECK(self->IsExceptionPending()); // OOME.
4523 return false;
4524 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004525 for (size_t i = 0; i < miranda_list_size; ++i) {
4526 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004527 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004528 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4529 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4530 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004531 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004532 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004533 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004534 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004535 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004536
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004537 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004538 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
4539 for (int i = 0; i < check_vtable->GetLength(); ++i) {
4540 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004541 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004542 }
4543
Ian Rogers7b078e82014-09-10 14:44:24 -07004544 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004545 return true;
4546}
4547
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004548bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004549 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004550 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004551}
4552
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004553bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004554 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004555 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004556}
4557
Brian Carlstromdbc05252011-09-09 01:59:59 -07004558struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004559 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4560 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004561 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07004562 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004563 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004564 // 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 -07004565 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4566 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004567 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00004568 if (type1 == Primitive::kPrimNot) {
4569 // Reference always goes first.
4570 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08004571 }
Vladimir Markod5777482014-11-12 17:02:02 +00004572 if (type2 == Primitive::kPrimNot) {
4573 // Reference always goes first.
4574 return false;
4575 }
4576 size_t size1 = Primitive::ComponentSize(type1);
4577 size_t size2 = Primitive::ComponentSize(type2);
4578 if (size1 != size2) {
4579 // Larger primitive types go first.
4580 return size1 > size2;
4581 }
4582 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
4583 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004584 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004585 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
4586 // by name and for equal names by type id index.
4587 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
4588 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004589 }
4590};
4591
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004592bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07004593 size_t* class_size) {
4594 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004595 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
4596 ArtField* const fields = is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004597
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004598 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004599 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004600 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00004601 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004602 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004603 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004604 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004605 CHECK(super_class->IsResolved())
4606 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004607 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004608 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004609 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004610
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004611 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004612
Brian Carlstromdbc05252011-09-09 01:59:59 -07004613 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004614 // minimizes disruption of C++ version such as Class and Method.
Mathieu Chartierc7853442015-03-27 14:35:38 -07004615 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07004616 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07004617 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07004618 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004619 grouped_and_sorted_fields.push_back(&fields[i]);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004620 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004621 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4622 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004623
Fred Shih381e4ca2014-08-25 17:24:27 -07004624 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07004625 size_t current_field = 0;
4626 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07004627 FieldGaps gaps;
4628
Brian Carlstromdbc05252011-09-09 01:59:59 -07004629 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004630 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004631 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004632 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004633 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004634 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004635 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004636 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
4637 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07004638 MemberOffset old_offset = field_offset;
4639 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
4640 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
4641 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004642 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07004643 grouped_and_sorted_fields.pop_front();
4644 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004645 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00004646 field_offset = MemberOffset(field_offset.Uint32Value() +
4647 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004648 }
Fred Shih381e4ca2014-08-25 17:24:27 -07004649 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
4650 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00004651 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4652 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4653 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4654 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07004655 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
4656 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07004657 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004658
Elliott Hughesadb460d2011-10-05 17:02:34 -07004659 // 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 -07004660 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004661 // We know there are no non-reference fields in the Reference classes, and we know
4662 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004663 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07004664 CHECK_STREQ(fields[num_fields - 1].GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004665 --num_reference_fields;
4666 }
4667
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004668 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004669 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004670 if (is_static) {
4671 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004672 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004673 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004674 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004675 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08004676 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08004677 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
4678 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08004679 } else {
4680 std::string temp;
4681 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
4682 size_t previous_size = klass->GetObjectSize();
4683 if (previous_size != 0) {
4684 // Make sure that we didn't originally have an incorrect size.
4685 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
4686 }
4687 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004688 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004689 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004690 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004691
4692 if (kIsDebugBuild) {
4693 // Make sure that the fields array is ordered by name but all reference
4694 // offsets are at the beginning as far as alignment allows.
4695 MemberOffset start_ref_offset = is_static
4696 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
4697 : klass->GetFirstReferenceInstanceFieldOffset();
4698 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
4699 num_reference_fields *
4700 sizeof(mirror::HeapReference<mirror::Object>));
4701 MemberOffset current_ref_offset = start_ref_offset;
4702 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004703 ArtField* field = &fields[i];
4704 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
4705 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
4706 << field->GetOffset();
Vladimir Marko76649e82014-11-10 18:32:59 +00004707 if (i != 0) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004708 ArtField* const prev_field = &fields[i - 1];
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004709 // NOTE: The field names can be the same. This is not possible in the Java language
4710 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
4711 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00004712 }
4713 Primitive::Type type = field->GetTypeAsPrimitiveType();
4714 bool is_primitive = type != Primitive::kPrimNot;
4715 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
4716 strcmp("referent", field->GetName()) == 0) {
4717 is_primitive = true; // We lied above, so we have to expect a lie here.
4718 }
4719 MemberOffset offset = field->GetOffsetDuringLinking();
4720 if (is_primitive) {
4721 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
4722 // Shuffled before references.
4723 size_t type_size = Primitive::ComponentSize(type);
4724 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
4725 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
4726 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
4727 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
4728 }
4729 } else {
4730 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
4731 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
4732 sizeof(mirror::HeapReference<mirror::Object>));
4733 }
4734 }
4735 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
4736 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004737 return true;
4738}
4739
Vladimir Marko76649e82014-11-10 18:32:59 +00004740// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004741void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004742 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004743 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004744 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004745 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004746 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004747 // Compute reference offsets unless our superclass overflowed.
4748 if (reference_offsets != mirror::Class::kClassWalkSuper) {
4749 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00004750 if (num_reference_fields != 0u) {
4751 // All of the fields that contain object references are guaranteed be grouped in memory
4752 // starting at an appropriately aligned address after super class object data.
4753 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
4754 sizeof(mirror::HeapReference<mirror::Object>));
4755 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004756 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00004757 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004758 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004759 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00004760 reference_offsets |= (0xffffffffu << start_bit) &
4761 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07004762 }
4763 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07004764 }
4765 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07004766 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004767}
4768
Mathieu Chartier590fee92013-09-13 13:46:47 -07004769mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004770 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004771 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004772 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004773 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004774 return resolved;
4775 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07004776 uint32_t utf16_length;
4777 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004778 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004779 dex_cache->SetResolvedString(string_idx, string);
4780 return string;
4781}
4782
Mathieu Chartier590fee92013-09-13 13:46:47 -07004783mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08004784 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004785 StackHandleScope<2> hs(Thread::Current());
4786 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
4787 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07004788 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4789}
4790
4791mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004792 Handle<mirror::DexCache> dex_cache,
4793 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004794 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004795 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004796 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08004797 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07004798 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08004799 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004800 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05004801 // TODO: we used to throw here if resolved's class loader was not the
4802 // boot class loader. This was to permit different classes with the
4803 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004804 dex_cache->SetResolvedType(type_idx, resolved);
4805 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08004806 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08004807 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08004808 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004809 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004810 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004811 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004812 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08004813 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08004814 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00004815 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08004816 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004817 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004818 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004819 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07004820 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004821 return resolved;
4822}
4823
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004824mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004825 Handle<mirror::DexCache> dex_cache,
4826 Handle<mirror::ClassLoader> class_loader,
4827 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07004828 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004829 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07004830 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07004831 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004832 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004833 return resolved;
4834 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004835 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004836 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004837 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004838 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07004839 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004840 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004841 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004842 // Scan using method_idx, this saves string compares but will only hit for matching dex
4843 // caches/files.
4844 switch (type) {
4845 case kDirect: // Fall-through.
4846 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004847 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004848 break;
4849 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004850 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004851 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004852 break;
4853 case kSuper: // Fall-through.
4854 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004855 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07004856 break;
4857 default:
4858 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07004859 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004860 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004861 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004862 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004863 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07004864 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07004865 switch (type) {
4866 case kDirect: // Fall-through.
4867 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08004868 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07004869 break;
4870 case kInterface:
4871 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004872 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07004873 break;
4874 case kSuper: // Fall-through.
4875 case kVirtual:
4876 resolved = klass->FindVirtualMethod(name, signature);
4877 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08004878 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004879 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004880 // If we found a method, check for incompatible class changes.
4881 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07004882 // Be a good citizen and update the dex cache to speed subsequent calls.
4883 dex_cache->SetResolvedMethod(method_idx, resolved);
4884 return resolved;
4885 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004886 // If we had a method, it's an incompatible-class-change error.
4887 if (resolved != nullptr) {
4888 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
4889 } else {
4890 // We failed to find the method which means either an access error, an incompatible class
4891 // change, or no such method. First try to find the method among direct and virtual methods.
4892 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4893 const Signature signature = dex_file.GetMethodSignature(method_id);
4894 switch (type) {
4895 case kDirect:
4896 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07004897 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004898 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
4899 // have had a resolved method before, which triggers the "true" branch above.
4900 break;
4901 case kInterface:
4902 case kVirtual:
4903 case kSuper:
4904 resolved = klass->FindDirectMethod(name, signature);
4905 break;
4906 }
4907
4908 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08004909 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004910 if (resolved != nullptr && referrer.Get() != nullptr) {
4911 mirror::Class* methods_class = resolved->GetDeclaringClass();
4912 mirror::Class* referring_class = referrer->GetDeclaringClass();
4913 if (!referring_class->CanAccess(methods_class)) {
4914 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4915 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004916 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004917 } else if (!referring_class->CanAccessMember(methods_class,
4918 resolved->GetAccessFlags())) {
4919 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004920 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004921 }
4922 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004923 if (!exception_generated) {
4924 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
4925 // interface methods and throw if we find the method there. If we find nothing, throw a
4926 // NoSuchMethodError.
4927 switch (type) {
4928 case kDirect:
4929 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004930 if (resolved != nullptr) {
4931 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4932 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004933 resolved = klass->FindInterfaceMethod(name, signature);
4934 if (resolved != nullptr) {
4935 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4936 } else {
4937 ThrowNoSuchMethodError(type, klass, name, signature);
4938 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004939 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004940 break;
4941 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004942 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08004943 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4944 } else {
4945 resolved = klass->FindVirtualMethod(name, signature);
4946 if (resolved != nullptr) {
4947 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
4948 } else {
4949 ThrowNoSuchMethodError(type, klass, name, signature);
4950 }
4951 }
4952 break;
4953 case kSuper:
4954 if (resolved != nullptr) {
4955 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004956 } else {
4957 ThrowNoSuchMethodError(type, klass, name, signature);
4958 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004959 break;
4960 case kVirtual:
4961 if (resolved != nullptr) {
4962 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
4963 } else {
4964 resolved = klass->FindInterfaceMethod(name, signature);
4965 if (resolved != nullptr) {
4966 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
4967 } else {
4968 ThrowNoSuchMethodError(type, klass, name, signature);
4969 }
4970 }
4971 break;
4972 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004973 }
Ian Rogers08f753d2012-08-24 14:35:25 -07004974 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08004975 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07004976 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07004977 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004978}
4979
Mathieu Chartierc7853442015-03-27 14:35:38 -07004980ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
4981 Handle<mirror::DexCache> dex_cache,
4982 Handle<mirror::ClassLoader> class_loader, bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004983 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004984 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07004985 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004986 return resolved;
4987 }
4988 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004989 Thread* const self = Thread::Current();
4990 StackHandleScope<1> hs(self);
4991 Handle<mirror::Class> klass(
4992 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07004993 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08004994 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004995 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07004996 }
4997
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07004998 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004999 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005000 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005001 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005002 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005003
Andreas Gampe58a5af82014-07-31 16:23:49 -07005004 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005005 const char* name = dex_file.GetFieldName(field_id);
5006 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5007 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005008 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005009 } else {
5010 resolved = klass->FindInstanceField(name, type);
5011 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005012 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005013 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005014 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005015 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005016 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07005017 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08005018 return resolved;
5019}
5020
Mathieu Chartierc7853442015-03-27 14:35:38 -07005021ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, uint32_t field_idx,
5022 Handle<mirror::DexCache> dex_cache,
5023 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005024 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005025 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005026 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005027 return resolved;
5028 }
5029 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005030 Thread* self = Thread::Current();
5031 StackHandleScope<1> hs(self);
5032 Handle<mirror::Class> klass(
5033 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005034 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005035 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005036 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005037 }
5038
Ian Rogersdfb325e2013-10-30 01:00:44 -07005039 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5040 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005041 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005042 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005043 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005044 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08005045 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005046 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005047 }
5048 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005049}
5050
Brian Carlstromea46f952013-07-30 01:26:50 -07005051const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005052 uint32_t* length) {
5053 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5054 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005055 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005056 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005057 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005058}
5059
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005060void ClassLinker::DumpAllClasses(int flags) {
5061 if (dex_cache_image_class_lookup_required_) {
5062 MoveImageClassesToClassTable();
5063 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005064 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5065 // 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 -08005066 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005067 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005068 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005069 for (GcRoot<mirror::Class>& it : class_table_) {
5070 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005071 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005072 }
5073
5074 for (size_t i = 0; i < all_classes.size(); ++i) {
5075 all_classes[i]->DumpClass(std::cerr, flags);
5076 }
5077}
5078
Elliott Hughes956af0f2014-12-11 14:34:28 -08005079static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005080 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005081 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5082 base -= sizeof(void*); // Move backward so that code_offset != 0.
5083 const uint32_t code_offset = sizeof(void*);
5084 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005085}
5086
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005087bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5088 return (entry_point == GetQuickResolutionStub()) ||
5089 (quick_resolution_trampoline_ == entry_point);
5090}
5091
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005092bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5093 return (entry_point == GetQuickToInterpreterBridge()) ||
5094 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5095}
5096
5097bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5098 return (entry_point == GetQuickGenericJniStub()) ||
5099 (quick_generic_jni_trampoline_ == entry_point);
5100}
5101
5102const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5103 return GetQuickGenericJniStub();
5104}
5105
Elliott Hughes956af0f2014-12-11 14:34:28 -08005106void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5107 const void* method_code) const {
5108 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005109 oat_method.LinkMethod(method);
5110 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005111}
5112
5113void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5114 if (!method->IsNative()) {
5115 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005116 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5117 } else {
5118 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005119 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005120 oat_method.LinkMethod(method);
5121 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005122 }
5123}
5124
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005125void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005126 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005127 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005128 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005129 MoveImageClassesToClassTable();
5130 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005131 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005132 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5133 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005134}
5135
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005136size_t ClassLinker::NumLoadedClasses() {
5137 if (dex_cache_image_class_lookup_required_) {
5138 MoveImageClassesToClassTable();
5139 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005140 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005141 // Only return non zygote classes since these are the ones which apps which care about.
5142 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005143}
5144
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005145pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005146 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005147}
5148
5149pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005150 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005151}
5152
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005153void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005154 DCHECK(!init_done_);
5155
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005156 DCHECK(klass != nullptr);
5157 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005158
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005159 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005160 DCHECK(class_roots != nullptr);
5161 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005162 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005163}
5164
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005165const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5166 static const char* class_roots_descriptors[] = {
5167 "Ljava/lang/Class;",
5168 "Ljava/lang/Object;",
5169 "[Ljava/lang/Class;",
5170 "[Ljava/lang/Object;",
5171 "Ljava/lang/String;",
5172 "Ljava/lang/DexCache;",
5173 "Ljava/lang/ref/Reference;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005174 "Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005175 "Ljava/lang/reflect/Field;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005176 "Ljava/lang/reflect/Proxy;",
5177 "[Ljava/lang/String;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005178 "[Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005179 "[Ljava/lang/reflect/Field;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005180 "Ljava/lang/ClassLoader;",
5181 "Ljava/lang/Throwable;",
5182 "Ljava/lang/ClassNotFoundException;",
5183 "Ljava/lang/StackTraceElement;",
5184 "Z",
5185 "B",
5186 "C",
5187 "D",
5188 "F",
5189 "I",
5190 "J",
5191 "S",
5192 "V",
5193 "[Z",
5194 "[B",
5195 "[C",
5196 "[D",
5197 "[F",
5198 "[I",
5199 "[J",
5200 "[S",
5201 "[Ljava/lang/StackTraceElement;",
5202 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005203 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5204 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005205
5206 const char* descriptor = class_roots_descriptors[class_root];
5207 CHECK(descriptor != nullptr);
5208 return descriptor;
5209}
5210
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005211std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5212 const {
5213 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005214 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005215}
5216
5217bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005218 const GcRoot<mirror::Class>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005219 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5220 return false;
5221 }
5222 std::string temp;
5223 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5224}
5225
5226std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5227 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005228 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005229}
5230
5231bool ClassLinker::ClassDescriptorHashEquals::operator()(
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005232 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005233 if (a.Read()->GetClassLoader() != b.second) {
5234 return false;
5235 }
5236 return a.Read()->DescriptorEquals(b.first);
5237}
5238
5239bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005240 const char* descriptor) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005241 return a.Read()->DescriptorEquals(descriptor);
5242}
5243
5244std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005245 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005246}
5247
Sebastien Hertz6963e442014-11-26 22:11:27 +01005248bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07005249 if (Runtime::Current()->UseJit()) {
5250 // JIT can have direct code pointers from any method to any other method.
5251 return true;
5252 }
Sebastien Hertz6963e442014-11-26 22:11:27 +01005253 // Non-image methods don't use direct code pointer.
5254 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5255 return false;
5256 }
5257 if (m->IsPrivate()) {
5258 // The method can only be called inside its own oat file. Therefore it won't be called using
5259 // its direct code if the oat file has been compiled in PIC mode.
Sebastien Hertz6963e442014-11-26 22:11:27 +01005260 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
Richard Uhler07b3c232015-03-31 15:57:54 -07005261 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01005262 if (oat_dex_file == nullptr) {
5263 // No oat file: the method has not been compiled.
5264 return false;
5265 }
5266 const OatFile* oat_file = oat_dex_file->GetOatFile();
5267 return oat_file != nullptr && !oat_file->IsPic();
5268 } else {
5269 // The method can be called outside its own oat file. Therefore it won't be called using its
5270 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5271 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5272 for (const OatFile* oat_file : oat_files_) {
5273 if (!oat_file->IsPic()) {
5274 return true;
5275 }
5276 }
5277 return false;
5278 }
5279}
5280
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005281jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
5282 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
5283 // We could move the jobject to the callers, but all call-sites do this...
5284 ScopedObjectAccessUnchecked soa(self);
5285
5286 // Register the dex files.
5287 for (const DexFile* dex_file : dex_files) {
5288 RegisterDexFile(*dex_file);
5289 }
5290
5291 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005292 StackHandleScope<10> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005293
Mathieu Chartierc7853442015-03-27 14:35:38 -07005294 ArtField* dex_elements_field =
5295 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005296
Mathieu Chartierc7853442015-03-27 14:35:38 -07005297 mirror::Class* dex_elements_class = dex_elements_field->GetType<true>();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005298 DCHECK(dex_elements_class != nullptr);
5299 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005300 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
5301 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005302 Handle<mirror::Class> h_dex_element_class =
5303 hs.NewHandle(dex_elements_class->GetComponentType());
5304
Mathieu Chartierc7853442015-03-27 14:35:38 -07005305 ArtField* element_file_field =
5306 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
5307 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005308
Mathieu Chartierc7853442015-03-27 14:35:38 -07005309 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
5310 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005311
5312 // Fill the elements array.
5313 int32_t index = 0;
5314 for (const DexFile* dex_file : dex_files) {
5315 StackHandleScope<3> hs2(self);
5316
5317 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(self, 1));
5318 DCHECK(h_long_array.Get() != nullptr);
5319 h_long_array->Set(0, reinterpret_cast<intptr_t>(dex_file));
5320
5321 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07005322 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005323 DCHECK(h_dex_file.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005324 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005325
5326 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
5327 DCHECK(h_element.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005328 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005329
5330 h_dex_elements->Set(index, h_element.Get());
5331 index++;
5332 }
5333 DCHECK_EQ(index, h_dex_elements->GetLength());
5334
5335 // Create DexPathList.
5336 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07005337 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005338 DCHECK(h_dex_path_list.Get() != nullptr);
5339 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005340 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005341
5342 // Create PathClassLoader.
5343 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
5344 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
5345 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
5346 h_path_class_class->AllocObject(self));
5347 DCHECK(h_path_class_loader.Get() != nullptr);
5348 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005349 ArtField* path_list_field =
5350 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
5351 DCHECK(path_list_field != nullptr);
5352 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005353
5354 // Make a pretend boot-classpath.
5355 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07005356 ArtField* const parent_field =
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005357 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07005358 "Ljava/lang/ClassLoader;");
5359 DCHECK(parent_field!= nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005360 mirror::Object* boot_cl =
5361 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005362 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005363
5364 // Make it a global ref and return.
5365 ScopedLocalRef<jobject> local_ref(
5366 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
5367 return soa.Env()->NewGlobalRef(local_ref.get());
5368}
5369
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005370} // namespace art