blob: bbbb9e0b81bbbf5523d6d95dca6829d68aa0e0bb [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogers700a4022014-05-19 16:49:03 -070020#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070021#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070022#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070023#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070024#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080027#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010028#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080030#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080031#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000032#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080033#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070035#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070036#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070037#include "gc/accounting/card_table-inl.h"
38#include "gc/accounting/heap_bitmap.h"
39#include "gc/heap.h"
40#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070041#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070042#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070043#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070044#include "leb128.h"
Ian Rogers1ff3c982014-08-12 02:30:58 -070045#include "method_helper-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080046#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070047#include "oat_file.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070048#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070049#include "mirror/art_field-inl.h"
50#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080051#include "mirror/class.h"
52#include "mirror/class-inl.h"
53#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070054#include "mirror/dex_cache-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/iftable-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080056#include "mirror/object-inl.h"
57#include "mirror/object_array-inl.h"
58#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070059#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070061#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080062#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070063#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070064#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070065#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070066#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070067#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070068#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070069#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080070#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070071#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070072
73namespace art {
74
Ian Rogers00f7d0e2012-07-19 15:28:27 -070075static void ThrowNoClassDefFoundError(const char* fmt, ...)
76 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070077 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070078static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070079 va_list args;
80 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080081 Thread* self = Thread::Current();
82 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
83 self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080084 va_end(args);
85}
86
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080087static void ThrowEarlierClassFailure(mirror::Class* c)
Ian Rogersb726dcb2012-09-05 08:57:23 -070088 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5c599942012-06-13 16:45:05 -070089 // The class failed to initialize on a previous attempt, so we want to throw
90 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
91 // failed in verification, in which case v2 5.4.1 says we need to re-throw
92 // the previous error.
Ian Rogers7b078e82014-09-10 14:44:24 -070093 Runtime* runtime = Runtime::Current();
94 bool is_compiler = runtime->IsCompiler();
95 if (!is_compiler) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -070096 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
97 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -070098
Elliott Hughes5c599942012-06-13 16:45:05 -070099 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800100 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700101 if (is_compiler) {
102 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
103 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
104 self->SetException(ThrowLocation(), pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700105 } else {
Ian Rogers7b078e82014-09-10 14:44:24 -0700106 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
107 if (c->GetVerifyErrorClass() != NULL) {
108 // TODO: change the verifier to store an _instance_, with a useful detail message?
109 std::string temp;
110 self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
111 PrettyDescriptor(c).c_str());
112 } else {
113 self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
114 PrettyDescriptor(c).c_str());
115 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700116 }
117}
118
Brian Carlstromb23eab12014-10-08 17:55:21 -0700119static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
120 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
121 if (VLOG_IS_ON(class_linker)) {
122 std::string temp;
123 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
124 << klass->GetLocation() << "\n" << Thread::Current()->GetException(nullptr)->Dump();
125 }
126}
127
128static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
129 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700130 Thread* self = Thread::Current();
131 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700132
133 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700134 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700135
136 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700137 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
138 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700139
Elliott Hughesa4f94742012-05-29 16:28:38 -0700140 // We only wrap non-Error exceptions; an Error can just be used as-is.
141 if (!is_error) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800142 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700143 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
144 nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700145 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700146 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700147}
148
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800149static size_t Hash(const char* s) {
150 // This is the java.lang.String hashcode for convenience, not interoperability.
151 size_t hash = 0;
152 for (; *s != '\0'; ++s) {
153 hash = hash * 31 + *s;
154 }
155 return hash;
156}
157
Fred Shih381e4ca2014-08-25 17:24:27 -0700158// Gap between two fields in object layout.
159struct FieldGap {
160 uint32_t start_offset; // The offset from the start of the object.
161 uint32_t size; // The gap size of 1, 2, or 4 bytes.
162};
163struct FieldGapsComparator {
164 explicit FieldGapsComparator() {
165 }
166 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
167 NO_THREAD_SAFETY_ANALYSIS {
168 // Sort by gap size, largest first.
169 return lhs.size > rhs.size;
170 }
171};
172typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
173
174// Adds largest aligned gaps to queue of gaps.
175void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
176 DCHECK(gaps != nullptr);
177
178 uint32_t current_offset = gap_start;
179 while (current_offset != gap_end) {
180 size_t remaining = gap_end - current_offset;
181 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
182 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
183 current_offset += sizeof(uint32_t);
184 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
185 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
186 current_offset += sizeof(uint16_t);
187 } else {
188 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
189 current_offset += sizeof(uint8_t);
190 }
191 DCHECK_LE(current_offset, gap_end) << "Overran gap";
192 }
193}
194// Shuffle fields forward, making use of gaps whenever possible.
195template<int n>
196static void ShuffleForward(const size_t num_fields, size_t* current_field_idx,
197 MemberOffset* field_offset,
198 mirror::ObjectArray<mirror::ArtField>* fields,
199 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
200 FieldGaps* gaps)
201 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
202 DCHECK(current_field_idx != nullptr);
203 DCHECK(grouped_and_sorted_fields != nullptr);
204 DCHECK(fields != nullptr || (num_fields == 0 && grouped_and_sorted_fields->empty()));
205 DCHECK(gaps != nullptr);
206 DCHECK(field_offset != nullptr);
207
208 DCHECK(IsPowerOfTwo(n));
209 while (!grouped_and_sorted_fields->empty()) {
210 mirror::ArtField* field = grouped_and_sorted_fields->front();
211 Primitive::Type type = field->GetTypeAsPrimitiveType();
212 if (Primitive::ComponentSize(type) < n) {
213 break;
214 }
215 if (!IsAligned<n>(field_offset->Uint32Value())) {
216 MemberOffset old_offset = *field_offset;
217 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
218 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
219 }
220 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
221 grouped_and_sorted_fields->pop_front();
222 fields->Set<false>(*current_field_idx, field);
223 if (!gaps->empty() && gaps->top().size >= n) {
224 FieldGap gap = gaps->top();
225 gaps->pop();
226 DCHECK(IsAligned<n>(gap.start_offset));
227 field->SetOffset(MemberOffset(gap.start_offset));
228 if (gap.size > n) {
229 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
230 }
231 } else {
232 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
233 field->SetOffset(*field_offset);
234 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
235 }
236 ++(*current_field_idx);
237 }
238}
239
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800240ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700241 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700242 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700243 dex_cache_image_class_lookup_required_(false),
244 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800245 class_roots_(nullptr),
246 array_iftable_(nullptr),
247 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700248 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800249 log_new_dex_caches_roots_(false),
250 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700251 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800252 portable_resolution_trampoline_(nullptr),
253 quick_resolution_trampoline_(nullptr),
254 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800255 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100256 quick_generic_jni_trampoline_(nullptr),
257 quick_to_interpreter_bridge_trampoline_(nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -0800258 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700259}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700260
Alex Light64ad14d2014-08-19 14:23:13 -0700261void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800262 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700263 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700264
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700265 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700266
Elliott Hughes30646832011-10-13 16:59:46 -0700267 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700268 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700269 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700270 // 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 -0800271 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700272 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
273 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700274 heap->AllocNonMovableObject<true>(self, nullptr,
275 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700276 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700277 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700278 mirror::Class::SetClassClass(java_lang_Class.Get());
279 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700280 if (kUseBakerOrBrooksReadBarrier) {
281 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800282 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700283 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700284 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800285 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800286 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700287
Elliott Hughes418d20f2011-09-22 14:00:39 -0700288 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700289 Handle<mirror::Class> class_array_class(hs.NewHandle(
290 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700291 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700292
Ian Rogers23435d02012-09-24 11:23:12 -0700293 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700294 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
295 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700296 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700297 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700298 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700299 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700300
Ian Rogers23435d02012-09-24 11:23:12 -0700301 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700302 Handle<mirror::Class> object_array_class(hs.NewHandle(
303 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700304 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700305
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700306 // Setup the char (primitive) class to be used for char[].
307 Handle<mirror::Class> char_class(hs.NewHandle(
308 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700309 // The primitive char class won't be initialized by
310 // InitializePrimitiveClass until line 459, but strings (and
311 // internal char arrays) will be allocated before that and the
312 // component size, which is computed from the primitive type, needs
313 // to be set here.
314 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700315
Ian Rogers23435d02012-09-24 11:23:12 -0700316 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700317 Handle<mirror::Class> char_array_class(hs.NewHandle(
318 AllocClass(self, java_lang_Class.Get(),
319 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700320 char_array_class->SetComponentType(char_class.Get());
321 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700322
Ian Rogers23435d02012-09-24 11:23:12 -0700323 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700324 Handle<mirror::Class> java_lang_String(hs.NewHandle(
325 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700326 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700327 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700328 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400329
Fred Shih4ee7a662014-07-11 09:59:27 -0700330 // Setup Reference.
331 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
332 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
333 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
334 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
335 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
336
Ian Rogers23435d02012-09-24 11:23:12 -0700337 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700338 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
339 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
340 kClassRootsMax));
341 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700342 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
343 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
344 SetClassRoot(kClassArrayClass, class_array_class.Get());
345 SetClassRoot(kObjectArrayClass, object_array_class.Get());
346 SetClassRoot(kCharArrayClass, char_array_class.Get());
347 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700348 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349
350 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700351 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
352 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
353 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
354 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
355 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
356 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
357 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
358 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359
Ian Rogers23435d02012-09-24 11:23:12 -0700360 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700361 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700362
Ian Rogers23435d02012-09-24 11:23:12 -0700363 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700364 Handle<mirror::Class> int_array_class(hs.NewHandle(
365 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700366 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700367 mirror::IntArray::SetArrayClass(int_array_class.Get());
368 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700369
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());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700377 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378
Brian Carlstromf3632832014-05-20 15:36:53 -0700379 // Constructor, Field, Method, and AbstractMethod are necessary so
380 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700381 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
382 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700383 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700384 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700385 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700386 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700387 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700388
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700389 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
390 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700391 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700392 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700393 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700394 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700395
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700396 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700397
398 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700399 Handle<mirror::Class> object_array_string(hs.NewHandle(
400 AllocClass(self, java_lang_Class.Get(),
401 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700402 object_array_string->SetComponentType(java_lang_String.Get());
403 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700404
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700405 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
406 AllocClass(self, java_lang_Class.Get(),
407 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700408 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
409 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700410
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700411 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
412 AllocClass(self, java_lang_Class.Get(),
413 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700414 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
415 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700416
Ian Rogers23435d02012-09-24 11:23:12 -0700417 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
418 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
419 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700420 CHECK_NE(0U, boot_class_path.size());
421 for (size_t i = 0; i != boot_class_path.size(); ++i) {
422 const DexFile* dex_file = boot_class_path[i];
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700423 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700424 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700425 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700426
427 // now we can use FindSystemClass
428
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700429 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700430 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
431 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700432
Jeff Hao88474b42013-10-23 16:24:40 -0700433 // Create runtime resolution and imt conflict methods. Also setup the default imt.
434 Runtime* runtime = Runtime::Current();
435 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
436 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
437 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
438
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700439 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
440 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700441 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700442 if (!runtime->IsCompiler()) {
443 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700444 quick_resolution_trampoline_ = GetQuickResolutionStub();
445 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
446 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700447 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700448
Mathieu Chartier66f19252012-09-18 08:57:04 -0700449 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700450 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800451 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700452 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700453 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700454 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800455 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700456 std::ostringstream os1, os2;
457 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
458 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
459 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
460 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700461 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800462 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700463 CHECK_EQ(java_lang_String.Get(), String_class);
464 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700465 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700466
Ian Rogers23435d02012-09-24 11:23:12 -0700467 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800468 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800469 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470
Ian Rogers98379392014-02-24 16:53:16 -0800471 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800472 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700473
Ian Rogers98379392014-02-24 16:53:16 -0800474 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700475 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476
Ian Rogers98379392014-02-24 16:53:16 -0800477 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800478 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700479
Ian Rogers98379392014-02-24 16:53:16 -0800480 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700481 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700482
Ian Rogers98379392014-02-24 16:53:16 -0800483 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800484 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700485
Ian Rogers98379392014-02-24 16:53:16 -0800486 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800487 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700488
Ian Rogers98379392014-02-24 16:53:16 -0800489 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800490 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700491
Ian Rogers98379392014-02-24 16:53:16 -0800492 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700493 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700494
Ian Rogers98379392014-02-24 16:53:16 -0800495 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700496 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700497
Ian Rogers23435d02012-09-24 11:23:12 -0700498 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800499 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700500 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800501 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700502 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700503 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
504 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700505 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700506 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700507 array_iftable->SetInterface(0, java_lang_Cloneable);
508 array_iftable->SetInterface(1, java_io_Serializable);
509 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700510
Ian Rogers23435d02012-09-24 11:23:12 -0700511 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700512 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
513 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
514 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
515 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700516 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700517 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800518 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700519 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700520
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700521 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800522 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700523 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700524
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700525 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800526 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700527 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700528
Brian Carlstromf3632832014-05-20 15:36:53 -0700529 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700530 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700531 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700532
Brian Carlstromea46f952013-07-30 01:26:50 -0700533 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700534 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700535 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700536
Brian Carlstromea46f952013-07-30 01:26:50 -0700537 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700538 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700539 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700540
Ian Rogers23435d02012-09-24 11:23:12 -0700541 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700542
Ian Rogers23435d02012-09-24 11:23:12 -0700543 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800544 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700545 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
546
Brian Carlstrom1f870082011-08-23 16:02:11 -0700547 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700548 // finish initializing Reference class
549 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
550 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
551 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
552 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
553 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700554 mirror::Class* java_lang_ref_FinalizerReference =
555 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700556 java_lang_ref_FinalizerReference->SetAccessFlags(
557 java_lang_ref_FinalizerReference->GetAccessFlags() |
558 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700559 mirror::Class* java_lang_ref_PhantomReference =
560 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700561 java_lang_ref_PhantomReference->SetAccessFlags(
562 java_lang_ref_PhantomReference->GetAccessFlags() |
563 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700564 mirror::Class* java_lang_ref_SoftReference =
565 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700566 java_lang_ref_SoftReference->SetAccessFlags(
567 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700568 mirror::Class* java_lang_ref_WeakReference =
569 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700570 java_lang_ref_WeakReference->SetAccessFlags(
571 java_lang_ref_WeakReference->GetAccessFlags() |
572 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700573
Ian Rogers23435d02012-09-24 11:23:12 -0700574 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800575 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700576 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700577 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
578
jeffhao8cd6dda2012-02-22 10:15:34 -0800579 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700580 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800581 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800582 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700583 SetClassRoot(kJavaLangClassNotFoundException,
584 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800585 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700586 SetClassRoot(kJavaLangStackTraceElementArrayClass,
587 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800588 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700589
Ian Rogers98379392014-02-24 16:53:16 -0800590 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700591
Brian Carlstroma004aa92012-02-08 18:05:09 -0800592 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700593}
594
Ian Rogers98379392014-02-24 16:53:16 -0800595void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800596 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700597
598 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700599 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700600 // as the types of the field can't be resolved prior to the runtime being
601 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800602 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700603 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800604 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800605
Brian Carlstromea46f952013-07-30 01:26:50 -0700606 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700607 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
608 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700609
Brian Carlstromea46f952013-07-30 01:26:50 -0700610 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700611 CHECK_STREQ(queue->GetName(), "queue");
612 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700613
Brian Carlstromea46f952013-07-30 01:26:50 -0700614 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700615 CHECK_STREQ(queueNext->GetName(), "queueNext");
616 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700617
Brian Carlstromea46f952013-07-30 01:26:50 -0700618 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700619 CHECK_STREQ(referent->GetName(), "referent");
620 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700621
Brian Carlstromea46f952013-07-30 01:26:50 -0700622 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700623 CHECK_STREQ(zombie->GetName(), "zombie");
624 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700625
Brian Carlstroma663ea52011-08-19 23:33:41 -0700626 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700627 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700628 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800629 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700630 CHECK(klass != nullptr);
631 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700632 // note SetClassRoot does additional validation.
633 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700634 }
635
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700636 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700637
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700638 // disable the slow paths in FindClass and CreatePrimitiveClass now
639 // that Object, Class, and Object[] are setup
640 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700641
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800642 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700643}
644
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700645void ClassLinker::RunRootClinits() {
646 Thread* self = Thread::Current();
647 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800648 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700649 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700650 StackHandleScope<1> hs(self);
651 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700652 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700653 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700654 }
655 }
656}
657
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700658bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800659 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000660 const char* oat_cache_filename,
661 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700662 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700663 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800664
Ian Rogers1d54e732013-05-02 21:10:01 -0700665 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800666 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700667 if (heap->GetImageSpace() == nullptr) {
668 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
669 // out of space anyway it might not matter.
670 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
671 "without an image.", dex_filename);
672 return false;
673 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700674 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800675
Brian Carlstrom6449c622014-02-10 23:48:36 -0800676 std::string dex_file_option("--dex-file=");
677 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800678
Brian Carlstrom6449c622014-02-10 23:48:36 -0800679 std::string oat_fd_option("--oat-fd=");
680 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800681
Brian Carlstrom6449c622014-02-10 23:48:36 -0800682 std::string oat_location_option("--oat-location=");
683 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800684
Brian Carlstrom6449c622014-02-10 23:48:36 -0800685 std::vector<std::string> argv;
686 argv.push_back(dex2oat);
687 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800688 argv.push_back("-classpath");
689 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800690 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800691
Ian Rogers8afeb852014-04-02 14:55:49 -0700692 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800693
Jeff Hao4a200f52014-04-01 14:58:49 -0700694 if (!Runtime::Current()->IsVerificationEnabled()) {
695 argv.push_back("--compiler-filter=verify-none");
696 }
697
Alex Light6e183f22014-07-18 14:57:04 -0700698 if (Runtime::Current()->MustRelocateIfPossible()) {
699 argv.push_back("--runtime-arg");
700 argv.push_back("-Xrelocate");
701 } else {
702 argv.push_back("--runtime-arg");
703 argv.push_back("-Xnorelocate");
704 }
705
Brian Carlstrom6449c622014-02-10 23:48:36 -0800706 if (!kIsTargetBuild) {
707 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700708 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700709
Brian Carlstrom6449c622014-02-10 23:48:36 -0800710 argv.push_back(boot_image_option);
711 argv.push_back(dex_file_option);
712 argv.push_back(oat_fd_option);
713 argv.push_back(oat_location_option);
714 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800715 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800716 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700717 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800718
719 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700720}
721
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700722const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700723 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800724 if (kIsDebugBuild) {
725 for (size_t i = 0; i < oat_files_.size(); ++i) {
726 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700727 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800728 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700729 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
730 oat_files_.push_back(oat_file);
731 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800732}
733
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700734OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
735 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700736 OatFile* oat_file = space->ReleaseOatFile();
737 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700738 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700739 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700740}
741
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100742const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800743 const char* dex_location = dex_file.GetLocation().c_str();
744 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100745 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800746}
747
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100748const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
749 const char* dex_location,
750 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700751 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100752 for (const OatFile* oat_file : oat_files_) {
753 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700754
755 if (oat_location != nullptr) {
756 if (oat_file->GetLocation() != oat_location) {
757 continue;
758 }
759 }
760
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700761 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800762 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700763 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100764 if (oat_dex_file != nullptr) {
765 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800766 }
767 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100768 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800769}
770
Calin Juravle621962a2014-09-02 15:53:55 +0100771
772// Loads all multi dex files from the given oat file returning true on success.
773//
774// Parameters:
775// oat_file - the oat file to load from
776// dex_location - the dex location used to generate the oat file
777// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
778// generated - whether or not the oat_file existed before or was just (re)generated
779// error_msgs - any error messages will be appended here
780// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
781static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
782 const char* dex_location,
783 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700784 bool generated,
785 std::vector<std::string>* error_msgs,
786 std::vector<const DexFile*>* dex_files) {
787 if (oat_file == nullptr) {
788 return false;
789 }
790
791 size_t old_size = dex_files->size(); // To rollback on error.
792
793 bool success = true;
794 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100795 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700796 const char* next_name = next_name_str.c_str();
797
Calin Juravle621962a2014-09-02 15:53:55 +0100798 uint32_t next_location_checksum;
799 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700800 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100801 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
802 // When i=0 the multidex name should be the same as the location name. We already have the
803 // checksum it so we don't need to recompute it.
804 if (dex_location_checksum == nullptr) {
805 next_location_checksum_pointer = nullptr;
806 } else {
807 next_location_checksum = *dex_location_checksum;
808 }
809 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700810 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100811 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700812 }
813
814 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
815
816 if (oat_dex_file == nullptr) {
817 if (i == 0 && generated) {
818 std::string error_msg;
819 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100820 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700821 oat_file->GetLocation().c_str());
822 error_msgs->push_back(error_msg);
823 }
824 break; // Not found, done.
825 }
826
827 // Checksum test. Test must succeed when generated.
828 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100829 if (next_location_checksum_pointer != nullptr) {
830 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700831 }
832
833 if (success) {
834 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
835 if (dex_file == nullptr) {
836 success = false;
837 error_msgs->push_back(error_msg);
838 } else {
839 dex_files->push_back(dex_file);
840 }
841 }
842
843 // When we generated the file, we expect success, or something is terribly wrong.
844 CHECK_EQ(false, generated && !success)
845 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100846 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700847 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
848 }
849
850 if (dex_files->size() == old_size) {
851 success = false; // We did not even find classes.dex
852 }
853
854 if (success) {
855 return true;
856 } else {
857 // Free all the dex files we have loaded.
858 auto it = dex_files->begin() + old_size;
859 auto it_end = dex_files->end();
860 for (; it != it_end; it++) {
861 delete *it;
862 }
863 dex_files->erase(dex_files->begin() + old_size, it_end);
864
865 return false;
866 }
867}
868
869// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
870// complicates the loading process, as we should not use an iterative loading process, because that
871// would register the oat file and dex files that come before the broken one. Instead, check all
872// multidex ahead of time.
873bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
874 std::vector<std::string>* error_msgs,
875 std::vector<const DexFile*>* dex_files) {
876 // 1) Check whether we have an open oat file.
877 // This requires a dex checksum, use the "primary" one.
878 uint32_t dex_location_checksum;
879 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
880 bool have_checksum = true;
881 std::string checksum_error_msg;
882 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100883 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700884 dex_location_checksum_pointer = nullptr;
885 have_checksum = false;
886 }
887
888 bool needs_registering = false;
889
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100890 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
891 dex_location_checksum_pointer);
892 std::unique_ptr<const OatFile> open_oat_file(
893 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700894
895 // 2) If we do not have an open one, maybe there's one on disk already.
896
897 // In case the oat file is not open, we play a locking game here so
898 // that if two different processes race to load and register or generate
899 // (or worse, one tries to open a partial generated file) we will be okay.
900 // This is actually common with apps that use DexClassLoader to work
901 // around the dex method reference limit and that have a background
902 // service running in a separate process.
903 ScopedFlock scoped_flock;
904
905 if (open_oat_file.get() == nullptr) {
906 if (oat_location != nullptr) {
907 // Can only do this if we have a checksum, else error.
908 if (!have_checksum) {
909 error_msgs->push_back(checksum_error_msg);
910 return false;
911 }
912
913 std::string error_msg;
914
915 // We are loading or creating one in the future. Time to set up the file lock.
916 if (!scoped_flock.Init(oat_location, &error_msg)) {
917 error_msgs->push_back(error_msg);
918 return false;
919 }
920
Alex Lighta59dd802014-07-02 16:28:08 -0700921 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700922 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
923 oat_location, &error_msg));
924
925 if (open_oat_file.get() == nullptr) {
926 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
927 dex_location, oat_location, error_msg.c_str());
928 VLOG(class_linker) << compound_msg;
929 error_msgs->push_back(compound_msg);
930 }
931 } else {
932 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100933 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700934 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
935 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100936 kRuntimeISA, error_msgs,
937 &obsolete_file_cleanup_failed));
938 // There's no point in going forward and eventually try to regenerate the
939 // file if we couldn't remove the obsolete one. Mostly likely we will fail
940 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100941 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
942 if (obsolete_file_cleanup_failed) {
943 return false;
944 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700945 }
946 needs_registering = true;
947 }
948
949 // 3) If we have an oat file, check all contained multidex files for our dex_location.
950 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100951 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
952 dex_location_checksum_pointer,
953 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700954 if (success) {
955 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
956 if (needs_registering) {
957 // We opened the oat file, so we must register it.
958 RegisterOatFile(oat_file);
959 }
Alex Light9dcc4572014-08-14 14:16:26 -0700960 // If the file isn't executable we failed patchoat but did manage to get the dex files.
961 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700962 } else {
963 if (needs_registering) {
964 // We opened it, delete it.
965 open_oat_file.reset();
966 } else {
967 open_oat_file.release(); // Do not delete open oat files.
968 }
969 }
970
971 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
972
973 // Need a checksum, fail else.
974 if (!have_checksum) {
975 error_msgs->push_back(checksum_error_msg);
976 return false;
977 }
978
979 // Look in cache location if no oat_location is given.
980 std::string cache_location;
981 if (oat_location == nullptr) {
982 // Use the dalvik cache.
983 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
984 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
985 oat_location = cache_location.c_str();
986 }
987
Alex Light64ad14d2014-08-19 14:23:13 -0700988 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700989 // Definitely need to lock now.
990 if (!scoped_flock.HasFile()) {
991 std::string error_msg;
992 if (!scoped_flock.Init(oat_location, &error_msg)) {
993 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700994 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700995 }
996 }
997
Alex Light64ad14d2014-08-19 14:23:13 -0700998 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +0100999 // Create the oat file.
1000 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1001 oat_location, error_msgs));
1002 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001003
1004 // Failed, bail.
1005 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001006 std::string error_msg;
1007 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1008 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1009 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001010 return false;
1011 }
1012
1013 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001014 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1015 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001016 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001017 if (success) {
1018 RegisterOatFile(open_oat_file.release());
1019 return true;
1020 } else {
1021 return false;
1022 }
1023}
1024
1025const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1026 uint32_t dex_location_checksum,
1027 const char* oat_location,
1028 std::string* error_msg) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001029 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001030 !Runtime::Current()->IsCompiler(),
1031 error_msg));
1032 if (oat_file.get() == nullptr) {
1033 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1034 error_msg->c_str());
1035 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001036 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001037 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001038 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1039 if (image_space != nullptr) {
1040 const ImageHeader& image_header = image_space->GetImageHeader();
1041 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1042 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1043 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1044 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1045 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1046 actual_image_oat_checksum);
1047 return nullptr;
1048 }
1049
1050 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1051 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1052 if (expected_image_oat_offset != actual_image_oat_offset) {
1053 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1054 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1055 actual_image_oat_offset);
1056 return nullptr;
1057 }
1058 int32_t expected_patch_delta = image_header.GetPatchDelta();
1059 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1060 if (expected_patch_delta != actual_patch_delta) {
1061 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1062 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1063 return nullptr;
1064 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001065 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001066
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001067 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1068 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001069 if (oat_dex_file == nullptr) {
1070 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1071 dex_location);
1072 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001073 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001074 uint32_t expected_dex_checksum = dex_location_checksum;
1075 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1076 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001077 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1078 "found 0x%x", oat_location, expected_dex_checksum,
1079 actual_dex_checksum);
1080 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001081 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001082 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1083 if (dex_file.get() != nullptr) {
1084 return oat_file.release();
1085 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001086 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001087 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001088}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001089
Andreas Gampe833a4852014-05-21 18:46:59 -07001090const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1091 int fd, const char* oat_location,
1092 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001093 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001094 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001095 std::string error_msg;
1096 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001097 CHECK(!error_msg.empty());
1098 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001099 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001100 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001101 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001102 !Runtime::Current()->IsCompiler(),
1103 &error_msg));
1104 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001105 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1106 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001107 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001108 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001109 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001110
1111 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001112}
1113
Alex Light6e183f22014-07-18 14:57:04 -07001114bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1115 const InstructionSet instruction_set) {
1116 Runtime* runtime = Runtime::Current();
1117 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001118 if (image_space == nullptr) {
1119 return false;
1120 }
Alex Light6e183f22014-07-18 14:57:04 -07001121 uint32_t image_oat_checksum = 0;
1122 if (instruction_set == kRuntimeISA) {
1123 const ImageHeader& image_header = image_space->GetImageHeader();
1124 image_oat_checksum = image_header.GetOatChecksum();
1125 } else {
1126 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1127 image_space->GetImageLocation().c_str(), instruction_set));
1128 image_oat_checksum = image_header->GetOatChecksum();
1129 }
1130 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1131}
1132
1133bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1134 const InstructionSet instruction_set,
1135 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001136 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001137 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001138 if (image_space == nullptr) {
1139 *error_msg = "No image space for verification against";
1140 return false;
1141 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001142
1143 // If the requested instruction set is the same as the current runtime,
1144 // we can use the checksums directly. If it isn't, we'll have to read the
1145 // image header from the image for the right instruction set.
1146 uint32_t image_oat_checksum = 0;
1147 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001148 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001149 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001150 const ImageHeader& image_header = image_space->GetImageHeader();
1151 image_oat_checksum = image_header.GetOatChecksum();
1152 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001153 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001154 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001155 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001156 image_space->GetImageLocation().c_str(), instruction_set));
1157 image_oat_checksum = image_header->GetOatChecksum();
1158 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001159 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001160 }
1161 const OatHeader& oat_header = oat_file->GetOatHeader();
Alex Light6e183f22014-07-18 14:57:04 -07001162 bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1163 && (oat_header.GetImagePatchDelta() == image_patch_delta)
1164 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1165 if (!ret) {
1166 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1167 oat_file->GetLocation().c_str(),
1168 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1169 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1170 oat_file->GetOatHeader().GetImagePatchDelta(),
1171 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1172 }
1173 return ret;
1174}
1175
1176bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1177 const char* dex_location,
1178 uint32_t dex_location_checksum,
1179 const InstructionSet instruction_set,
1180 std::string* error_msg) {
1181 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1182 return false;
1183 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001184
Brian Carlstromf3632832014-05-20 15:36:53 -07001185 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1186 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001187 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001188 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1189 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001190 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1191 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001192 oat_file->GetLocation().c_str(),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001193 oat_dex_file->GetDexFileLocation().c_str(),
1194 oat_dex_file->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001195 }
1196 return false;
1197 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001198
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001199 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001200 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001201}
1202
Alex Lighta59dd802014-07-02 16:28:08 -07001203bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1204 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001205 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001206 std::string* error_msg) {
1207 CHECK(oat_file != nullptr);
1208 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001209 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001210 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001211 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1212 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1213 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001214 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001215 if (oat_dex_file == nullptr) {
1216 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001217 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001218 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001219 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001220 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001221 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001222 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001223 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001224 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001225 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001226 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001227 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001228 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001229 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001230 }
Alex Lighta59dd802014-07-02 16:28:08 -07001231 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001232}
1233
Andreas Gampe833a4852014-05-21 18:46:59 -07001234const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001235 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001236 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001237 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001238 std::vector<std::string>* error_msgs,
1239 bool* obsolete_file_cleanup_failed) {
1240 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001241 bool already_opened = false;
1242 std::string dex_location_str(dex_location);
1243 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1244 &already_opened,
1245 obsolete_file_cleanup_failed,
1246 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001247 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001248 if (oat_file.get() == nullptr) {
1249 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1250 dex_location));
1251 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001252 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001253 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1254 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001255 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1256 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001257 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001258 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001259 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001260 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001261 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1262 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1263 "dex location '%s'. Image checksum incorrect.",
1264 oat_file->GetLocation().c_str(), dex_location));
1265 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001266 } else {
1267 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001268 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001269}
1270
Brian Carlstromae826982011-11-09 01:33:42 -08001271const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001272 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001273 for (size_t i = 0; i < oat_files_.size(); i++) {
1274 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001275 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001276 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001277 return oat_file;
1278 }
1279 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001280 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001281}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001282
Alex Lighta59dd802014-07-02 16:28:08 -07001283const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1284 InstructionSet isa,
1285 bool *already_opened,
1286 bool *obsolete_file_cleanup_failed,
1287 std::vector<std::string>* error_msgs) {
1288 // Find out if we've already opened the file
1289 const OatFile* ret = nullptr;
1290 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1291 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1292 if (ret != nullptr) {
1293 *already_opened = true;
1294 return ret;
1295 }
1296
1297 std::string dalvik_cache;
1298 bool have_android_data = false;
1299 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001300 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001301 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001302 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001303 std::string cache_filename;
1304 if (have_dalvik_cache) {
1305 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1306 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1307 if (ret != nullptr) {
1308 *already_opened = true;
1309 return ret;
1310 }
1311 } else {
1312 // If we need to relocate we should just place odex back where it started.
1313 cache_filename = odex_filename;
1314 }
1315
1316 ret = nullptr;
1317
1318 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1319 //
1320 // Now we do the following:
1321 // 1) Try and open the odex version
1322 // 2) If present, checksum-verified & relocated correctly return it
1323 // 3) Close the odex version to free up its address space.
1324 // 4) Try and open the cache version
1325 // 5) If present, checksum-verified & relocated correctly return it
1326 // 6) Close the cache version to free up its address space.
1327 // 7) If we should relocate:
1328 // a) If we have opened and checksum-verified the odex version relocate it to
1329 // 'cache_filename' and return it
1330 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1331 // it. This should not happen often (I think only the run-test's will hit this case).
1332 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1333 // this point.
1334 // 9) Return nullptr
1335
1336 *already_opened = false;
1337 const Runtime* runtime = Runtime::Current();
1338 CHECK(runtime != nullptr);
1339 bool executable = !runtime->IsCompiler();
1340
1341 std::string odex_error_msg;
1342 bool should_patch_system = false;
1343 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001344 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001345 {
1346 // There is a high probability that these both these oat files map similar/the same address
1347 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001348 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001349 executable, &odex_error_msg));
1350 if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1351 &odex_checksum_verified,
1352 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001353 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001354 } else {
1355 if (odex_checksum_verified) {
1356 // We can just relocate
1357 should_patch_system = true;
1358 odex_error_msg = "Image Patches are incorrect";
1359 }
1360 if (odex_oat_file.get() != nullptr) {
1361 have_system_odex = true;
1362 }
Alex Lighta59dd802014-07-02 16:28:08 -07001363 }
1364 }
1365
Alex Lighta59dd802014-07-02 16:28:08 -07001366 std::string cache_error_msg;
1367 bool should_patch_cache = false;
1368 bool cache_checksum_verified = false;
1369 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001370 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001371 executable, &cache_error_msg));
1372 if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1373 &cache_checksum_verified,
1374 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001375 return cache_oat_file.release();
1376 } else if (cache_checksum_verified) {
1377 // We can just relocate
1378 should_patch_cache = true;
1379 cache_error_msg = "Image Patches are incorrect";
1380 }
1381 } else if (have_android_data) {
1382 // dalvik_cache does not exist but android data does. This means we should be able to create
1383 // it, so we should try.
1384 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1385 }
1386
1387 ret = nullptr;
1388 std::string error_msg;
1389 if (runtime->CanRelocate()) {
1390 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001391 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1392 if (space != nullptr) {
1393 const std::string& image_location = space->GetImageLocation();
1394 if (odex_checksum_verified && should_patch_system) {
1395 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1396 } else if (cache_checksum_verified && should_patch_cache) {
1397 CHECK(have_dalvik_cache);
1398 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1399 }
Alex Light84d76052014-08-22 17:49:35 -07001400 } else if (have_system_odex) {
1401 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001402 }
1403 }
1404 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1405 // implicitly: were able to fine where the cached version is but we were unable to use it,
1406 // either as a destination for relocation or to open a file. We should delete it if it is
1407 // there.
1408 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1409 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1410 "searching for dex file %s: %s",
1411 cache_filename.c_str(), dex_location.c_str(),
1412 strerror(errno));
1413 error_msgs->push_back(rm_error_msg);
1414 VLOG(class_linker) << rm_error_msg;
1415 // Let the caller know that we couldn't remove the obsolete file.
1416 // This is a good indication that further writes may fail as well.
1417 *obsolete_file_cleanup_failed = true;
1418 }
1419 }
1420 if (ret == nullptr) {
1421 VLOG(class_linker) << error_msg;
1422 error_msgs->push_back(error_msg);
1423 std::string relocation_msg;
1424 if (runtime->CanRelocate()) {
1425 relocation_msg = StringPrintf(" and relocation failed");
1426 }
1427 if (have_dalvik_cache && cache_checksum_verified) {
1428 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1429 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1430 cache_filename.c_str(), cache_error_msg.c_str(),
1431 relocation_msg.c_str());
1432 } else {
1433 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1434 "dalvik_cache availible)%s.", odex_filename.c_str(),
1435 odex_error_msg.c_str(), relocation_msg.c_str());
1436 }
1437 VLOG(class_linker) << error_msg;
1438 error_msgs->push_back(error_msg);
1439 }
1440 return ret;
1441}
1442
Alex Light9dcc4572014-08-14 14:16:26 -07001443const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1444 InstructionSet isa,
1445 std::string* error_msg) {
1446 // We open it non-executable
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001447 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001448 if (output.get() == nullptr) {
1449 return nullptr;
1450 }
Alex Light84d76052014-08-22 17:49:35 -07001451 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1452 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001453 return output.release();
1454 } else {
1455 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1456 oat_path.c_str());
1457 return nullptr;
1458 }
1459}
1460
Alex Lighta59dd802014-07-02 16:28:08 -07001461const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1462 const std::string& output_oat,
1463 const std::string& image_location,
1464 InstructionSet isa,
1465 std::string* error_msg) {
Alex Light64ad14d2014-08-19 14:23:13 -07001466 if (!Runtime::Current()->GetHeap()->HasImageSpace()) {
1467 // We don't have an image space so there is no point in trying to patchoat.
1468 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1469 << "running without an image. Attempting to use oat file for interpretation.";
1470 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1471 }
Alex Light9dcc4572014-08-14 14:16:26 -07001472 if (!Runtime::Current()->IsDex2OatEnabled()) {
1473 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1474 // input_oat but make sure we only do interpretation on it's dex files.
1475 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1476 << "disabled. Attempting to use oat file for interpretation";
1477 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1478 }
Alex Lighta59dd802014-07-02 16:28:08 -07001479 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
1480 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1481
1482 std::string isa_arg("--instruction-set=");
1483 isa_arg += GetInstructionSetString(isa);
1484 std::string input_oat_filename_arg("--input-oat-file=");
1485 input_oat_filename_arg += input_oat;
1486 std::string output_oat_filename_arg("--output-oat-file=");
1487 output_oat_filename_arg += output_oat;
1488 std::string patched_image_arg("--patched-image-location=");
1489 patched_image_arg += image_location;
1490
1491 std::vector<std::string> argv;
1492 argv.push_back(patchoat);
1493 argv.push_back(isa_arg);
1494 argv.push_back(input_oat_filename_arg);
1495 argv.push_back(output_oat_filename_arg);
1496 argv.push_back(patched_image_arg);
1497
1498 std::string command_line(Join(argv, ' '));
1499 LOG(INFO) << "Relocate Oat File: " << command_line;
1500 bool success = Exec(argv, error_msg);
1501 if (success) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001502 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001503 !Runtime::Current()->IsCompiler(), error_msg));
1504 bool checksum_verified = false;
1505 if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1506 return output.release();
1507 } else if (output.get() != nullptr) {
1508 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1509 "but output file '%s' failed verifcation: %s",
1510 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1511 } else {
1512 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1513 "but was unable to open output file '%s': %s",
1514 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1515 }
Alex Light9dcc4572014-08-14 14:16:26 -07001516 } else if (!Runtime::Current()->IsCompiler()) {
1517 // patchoat failed which means we probably don't have enough room to place the output oat file,
1518 // instead of failing we should just run the interpreter from the dex files in the input oat.
1519 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1520 << "for interpretation. patchoat failure was: " << *error_msg;
1521 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001522 } else {
1523 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1524 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1525 error_msg->c_str());
1526 }
1527 return nullptr;
1528}
1529
1530int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1531 Runtime* runtime = Runtime::Current();
1532 int32_t real_patch_delta;
1533 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001534 CHECK(image_space != nullptr);
Alex Lighta59dd802014-07-02 16:28:08 -07001535 if (isa == Runtime::Current()->GetInstructionSet()) {
1536 const ImageHeader& image_header = image_space->GetImageHeader();
1537 real_patch_delta = image_header.GetPatchDelta();
1538 } else {
1539 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1540 image_space->GetImageLocation().c_str(), isa));
1541 real_patch_delta = image_header->GetPatchDelta();
1542 }
1543 const OatHeader& oat_header = oat_file->GetOatHeader();
1544 return real_patch_delta - oat_header.GetImagePatchDelta();
1545}
1546
1547bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1548 bool* checksum_verified,
1549 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001550 Runtime* runtime = Runtime::Current();
Alex Lighta59dd802014-07-02 16:28:08 -07001551 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001552 if (image_space == nullptr) {
1553 *error_msg = "No image space present";
1554 return false;
1555 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001556 uint32_t real_image_checksum;
1557 void* real_image_oat_offset;
1558 int32_t real_patch_delta;
1559 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001560 const ImageHeader& image_header = image_space->GetImageHeader();
1561 real_image_checksum = image_header.GetOatChecksum();
1562 real_image_oat_offset = image_header.GetOatDataBegin();
1563 real_patch_delta = image_header.GetPatchDelta();
1564 } else {
1565 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1566 image_space->GetImageLocation().c_str(), isa));
1567 real_image_checksum = image_header->GetOatChecksum();
1568 real_image_oat_offset = image_header->GetOatDataBegin();
1569 real_patch_delta = image_header->GetPatchDelta();
1570 }
1571
1572 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001573 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001574
1575 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1576 *checksum_verified = oat_image_checksum == real_image_checksum;
1577 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001578 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1579 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001580 }
1581
1582 void* oat_image_oat_offset =
1583 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1584 bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1585 if (!offset_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001586 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1587 real_image_oat_offset, oat_image_oat_offset);
Alex Lighta59dd802014-07-02 16:28:08 -07001588 }
1589
1590 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1591 bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1592 if (!patch_delta_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001593 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, received 0x%x)",
1594 real_patch_delta, oat_patch_delta);
Alex Lighta59dd802014-07-02 16:28:08 -07001595 }
1596
1597 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001598 if (!ret) {
1599 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001600 }
1601 return ret;
1602}
1603
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001604const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1605 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001606 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001607 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001608 return oat_file;
1609 }
1610
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001611 return OatFile::Open(oat_location, oat_location, nullptr, !Runtime::Current()->IsCompiler(),
1612 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001613}
1614
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001615static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001616 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001617 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1618
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001619 DCHECK(obj != nullptr);
1620 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001621
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001622 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001623 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001624 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001625 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers848871b2013-08-05 10:56:33 -07001626 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001627 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1628 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001629 }
1630 }
1631 }
1632}
1633
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001634void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001635 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001636 CHECK(!init_done_);
1637
Mathieu Chartier590fee92013-09-13 13:46:47 -07001638 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001639 gc::Heap* heap = Runtime::Current()->GetHeap();
1640 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001641 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001642 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001643 OatFile& oat_file = GetImageOatFile(space);
1644 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1645 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001646 const char* image_file_location = oat_file.GetOatHeader().
1647 GetStoreValueByKey(OatHeader::kImageLocationKey);
1648 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001649 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1650 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001651 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1652 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001653 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001654 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001655 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1656 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1657 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001658
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001659 StackHandleScope<1> hs(self);
1660 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1661 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1662 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001663 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001664
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001665 // Special case of setting up the String class early so that we can test arbitrary objects
1666 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001667 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001668
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001669 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001670 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001671 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001672 StackHandleScope<1> hs(self);
1673 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001674 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001675 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1676 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001677 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001678 std::string error_msg;
1679 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001680 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001681 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001682 << " from within oat file " << oat_file.GetLocation()
1683 << " error '" << error_msg << "'";
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001684 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001685
1686 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1687
1688 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001689 }
1690
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001691 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1692 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001693 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001694
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001695 // Set entry point to interpreter if in InterpretOnly mode.
1696 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001697 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001698 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001699 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001700
1701 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001702 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001703 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001704
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001705 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001706 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1707 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001708 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001709 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001710 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001711 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1712 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1713 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1714 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1715 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1716 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1717 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1718 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1719 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1720 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001721
Ian Rogers98379392014-02-24 16:53:16 -08001722 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001723
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001724 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001725}
1726
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001727void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1728 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1729 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001730 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1731 it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001732 }
1733 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1734 for (auto& pair : new_class_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001735 mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1736 pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1737 mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1738 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001739 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1740 // corresponding object. This is slow, but luckily for us, this may only happen with a
1741 // concurrent moving GC.
1742 for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1743 it != end && it->first == pair.first; ++it) {
1744 // If the class stored matches the old class, update it to the new value.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001745 if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1746 it->second = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001747 }
1748 }
1749 }
1750 }
1751 }
1752 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1753 new_class_roots_.clear();
1754 }
1755 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1756 log_new_class_table_roots_ = true;
1757 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1758 log_new_class_table_roots_ = false;
1759 }
1760 // We deliberately ignore the class roots in the image since we
1761 // handle image roots by using the MS/CMS rescanning of dirty cards.
1762}
1763
Brian Carlstroma663ea52011-08-19 23:33:41 -07001764// Keep in sync with InitCallback. Anything we visit, we need to
1765// reinit references to when reinitializing a ClassLinker from a
1766// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001767void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001768 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001769 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001770 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001771 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001772 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001773 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1774 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001775 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001776 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1777 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001778 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001779 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001780 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001781 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1782 new_dex_cache_roots_.clear();
1783 }
1784 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1785 log_new_dex_caches_roots_ = true;
1786 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1787 log_new_dex_caches_roots_ = false;
1788 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001789 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001790 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001791 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1792 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001793 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001794 if (!find_array_class_cache_[i].IsNull()) {
1795 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001796 }
1797 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001798}
1799
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001800void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1801 if (dex_cache_image_class_lookup_required_) {
1802 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001803 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001804 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001805 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001806 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1807 mirror::Class* c = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07001808 if (!visitor(c, arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001809 return;
1810 }
1811 }
1812}
1813
Ian Rogersdbf3be02014-08-29 15:40:08 -07001814static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001815 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001816 classes->insert(c);
1817 return true;
1818}
1819
Ian Rogersdbf3be02014-08-29 15:40:08 -07001820struct GetClassesVisitorArrayArg {
1821 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1822 int32_t index;
1823 bool success;
1824};
1825
1826static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1827 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1828 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1829 if (arg->index < (*arg->classes)->GetLength()) {
1830 (*arg->classes)->Set(arg->index, c);
1831 arg->index++;
1832 return true;
1833 } else {
1834 arg->success = false;
1835 return false;
1836 }
1837}
1838
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001839void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001840 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1841 // is avoiding duplicates.
1842 if (!kMovingClasses) {
1843 std::set<mirror::Class*> classes;
1844 VisitClasses(GetClassesVisitorSet, &classes);
1845 for (mirror::Class* klass : classes) {
1846 if (!visitor(klass, arg)) {
1847 return;
1848 }
1849 }
1850 } else {
1851 Thread* self = Thread::Current();
1852 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001853 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001854 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1855 GetClassesVisitorArrayArg local_arg;
1856 local_arg.classes = &classes;
1857 local_arg.success = false;
1858 // We size the array assuming classes won't be added to the class table during the visit.
1859 // If this assumption fails we iterate again.
1860 while (!local_arg.success) {
1861 size_t class_table_size;
1862 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001863 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogersdbf3be02014-08-29 15:40:08 -07001864 class_table_size = class_table_.size();
1865 }
1866 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1867 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1868 classes.Assign(
1869 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1870 CHECK(classes.Get() != nullptr); // OOME.
1871 local_arg.index = 0;
1872 local_arg.success = true;
1873 VisitClasses(GetClassesVisitorArray, &local_arg);
1874 }
1875 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1876 // If the class table shrank during creation of the clases array we expect null elements. If
1877 // the class table grew then the loop repeats. If classes are created after the loop has
1878 // finished then we don't visit.
1879 mirror::Class* klass = classes->Get(i);
1880 if (klass != nullptr && !visitor(klass, arg)) {
1881 return;
1882 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001883 }
1884 }
1885}
1886
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001887ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001888 mirror::Class::ResetClass();
1889 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001890 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001891 mirror::ArtField::ResetClass();
1892 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001893 mirror::BooleanArray::ResetArrayClass();
1894 mirror::ByteArray::ResetArrayClass();
1895 mirror::CharArray::ResetArrayClass();
1896 mirror::DoubleArray::ResetArrayClass();
1897 mirror::FloatArray::ResetArrayClass();
1898 mirror::IntArray::ResetArrayClass();
1899 mirror::LongArray::ResetArrayClass();
1900 mirror::ShortArray::ResetArrayClass();
1901 mirror::Throwable::ResetClass();
1902 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001903 STLDeleteElements(&boot_class_path_);
1904 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001905}
1906
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001907mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001908 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001909 StackHandleScope<16> hs(self);
1910 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1911 Handle<mirror::DexCache> dex_cache(
1912 hs.NewHandle(down_cast<mirror::DexCache*>(
1913 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1914 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001915 if (dex_cache.Get() == nullptr) {
1916 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001917 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001918 Handle<mirror::String>
1919 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001920 if (location.Get() == nullptr) {
1921 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001922 }
Ian Rogers700a4022014-05-19 16:49:03 -07001923 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001924 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001925 if (strings.Get() == nullptr) {
1926 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001927 }
Ian Rogers700a4022014-05-19 16:49:03 -07001928 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001929 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001930 if (types.Get() == nullptr) {
1931 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001932 }
Ian Rogers700a4022014-05-19 16:49:03 -07001933 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001934 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001935 if (methods.Get() == nullptr) {
1936 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001937 }
Ian Rogers700a4022014-05-19 16:49:03 -07001938 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001939 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001940 if (fields.Get() == nullptr) {
1941 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001942 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001943 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1944 fields.Get());
1945 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001946}
1947
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001948mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001949 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001950 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001951 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001952 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001953 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001954 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1955 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001956 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001957 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001958 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001959 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001960 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001961}
1962
Ian Rogers6fac4472014-02-25 17:01:10 -08001963mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001964 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001965}
1966
Brian Carlstromea46f952013-07-30 01:26:50 -07001967mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001968 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001969 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001970}
1971
Brian Carlstromea46f952013-07-30 01:26:50 -07001972mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001973 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001974 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001975}
1976
Mathieu Chartier590fee92013-09-13 13:46:47 -07001977mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1978 Thread* self, size_t length) {
1979 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1980 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001981}
1982
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001983mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1984 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001985 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001986
1987 // For temporary classes we must wait for them to be retired.
1988 if (init_done_ && klass->IsTemp()) {
1989 CHECK(!klass->IsResolved());
1990 if (klass->IsErroneous()) {
1991 ThrowEarlierClassFailure(klass);
1992 return nullptr;
1993 }
1994 StackHandleScope<1> hs(self);
1995 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1996 ObjectLock<mirror::Class> lock(self, h_class);
1997 // Loop and wait for the resolving thread to retire this class.
1998 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1999 lock.WaitIgnoringInterrupts();
2000 }
2001 if (h_class->IsErroneous()) {
2002 ThrowEarlierClassFailure(h_class.Get());
2003 return nullptr;
2004 }
2005 CHECK(h_class->IsRetired());
2006 // Get the updated class from class table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002007 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002008 }
2009
Brian Carlstromaded5f72011-10-07 17:15:04 -07002010 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002011 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002012 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002013 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2014 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002015 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002016 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2017 ThrowClassCircularityError(h_class.Get());
2018 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002019 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002020 }
2021 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002022 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002023 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002024 }
2025 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002026
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002027 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002028 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002029 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002030 }
2031 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002032 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002033 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002034 return klass;
2035}
2036
Ian Rogers68b56852014-08-29 20:19:11 -07002037typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2038
2039// Search a collection of DexFiles for a descriptor
2040ClassPathEntry FindInClassPath(const char* descriptor,
2041 const std::vector<const DexFile*>& class_path) {
2042 for (size_t i = 0; i != class_path.size(); ++i) {
2043 const DexFile* dex_file = class_path[i];
2044 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002045 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002046 return ClassPathEntry(dex_file, dex_class_def);
2047 }
2048 }
2049 // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002050 return ClassPathEntry(static_cast<const DexFile*>(nullptr),
2051 static_cast<const DexFile::ClassDef*>(nullptr));
Ian Rogers68b56852014-08-29 20:19:11 -07002052}
2053
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002054mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2055 Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002056 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002057 if (class_loader->GetClass() !=
2058 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2059 class_loader->GetParent()->GetClass() !=
2060 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2061 return nullptr;
2062 }
2063 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2064 // Check if this would be found in the parent boot class loader.
2065 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002066 mirror::Class* klass = LookupClass(self, descriptor, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002067 if (klass != nullptr) {
2068 return EnsureResolved(self, descriptor, klass);
2069 }
Ian Rogers7b078e82014-09-10 14:44:24 -07002070 klass = DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002071 *pair.second);
2072 if (klass != nullptr) {
2073 return klass;
2074 }
2075 CHECK(self->IsExceptionPending()) << descriptor;
2076 self->ClearException();
2077 } else {
2078 // RegisterDexFile may allocate dex caches (and cause thread suspension).
2079 StackHandleScope<3> hs(self);
2080 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2081 // We need to get the DexPathList and loop through it.
2082 Handle<mirror::ArtField> cookie_field =
2083 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2084 Handle<mirror::ArtField> dex_file_field =
2085 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002086 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002087 mirror::Object* dex_path_list =
2088 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2089 GetObject(class_loader.Get());
2090 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2091 cookie_field.Get() != nullptr) {
2092 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2093 mirror::Object* dex_elements_obj =
2094 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2095 GetObject(dex_path_list);
2096 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2097 // at the mCookie which is a DexFile vector.
2098 if (dex_elements_obj != nullptr) {
2099 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2100 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2101 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2102 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2103 if (element == nullptr) {
2104 // Should never happen, fall back to java code to throw a NPE.
2105 break;
2106 }
2107 mirror::Object* dex_file = dex_file_field->GetObject(element);
2108 if (dex_file != nullptr) {
2109 const uint64_t cookie = cookie_field->GetLong(dex_file);
2110 auto* dex_files =
2111 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2112 if (dex_files == nullptr) {
2113 // This should never happen so log a warning.
2114 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2115 break;
2116 }
2117 for (const DexFile* dex_file : *dex_files) {
2118 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
2119 if (dex_class_def != nullptr) {
2120 RegisterDexFile(*dex_file);
2121 mirror::Class* klass =
Ian Rogers7b078e82014-09-10 14:44:24 -07002122 DefineClass(self, descriptor, class_loader, *dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002123 if (klass == nullptr) {
2124 CHECK(self->IsExceptionPending()) << descriptor;
2125 self->ClearException();
2126 return nullptr;
2127 }
2128 return klass;
2129 }
2130 }
2131 }
2132 }
2133 }
2134 }
2135 }
2136 return nullptr;
2137}
2138
Ian Rogers98379392014-02-24 16:53:16 -08002139mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002140 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002141 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002142 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002143 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002144 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002145 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2146 // for primitive classes that aren't backed by dex files.
2147 return FindPrimitiveClass(descriptor[0]);
2148 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002149 // Find the class in the loaded classes table.
Ian Rogers7b078e82014-09-10 14:44:24 -07002150 mirror::Class* klass = LookupClass(self, descriptor, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002151 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002152 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002153 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002154 // Class is not yet loaded.
2155 if (descriptor[0] == '[') {
Ian Rogers98379392014-02-24 16:53:16 -08002156 return CreateArrayClass(self, descriptor, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002157 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002158 // The boot class loader, search the boot class path.
Ian Rogers68b56852014-08-29 20:19:11 -07002159 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2160 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002161 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2162 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002163 } else {
2164 // The boot class loader is searched ahead of the application class loader, failures are
2165 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2166 // trigger the chaining with a proper stack trace.
2167 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2168 self->SetException(ThrowLocation(), pre_allocated);
2169 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002170 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002171 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002172 // First try with the bootstrap class loader.
2173 if (class_loader.Get() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002174 klass = LookupClass(self, descriptor, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002175 if (klass != nullptr) {
2176 return EnsureResolved(self, descriptor, klass);
2177 }
2178 }
Ian Rogers63557452014-06-04 16:57:15 -07002179 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2180 // a NoClassDefFoundError being allocated.
Ian Rogers68b56852014-08-29 20:19:11 -07002181 ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2182 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002183 return DefineClass(self, descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2184 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002185 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002186 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002187 const std::vector<const DexFile*>* class_path;
2188 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002189 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002190 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002191 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002192 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2193 }
Ian Rogers68b56852014-08-29 20:19:11 -07002194 pair = FindInClassPath(descriptor, *class_path);
2195 if (pair.second != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002196 return DefineClass(self, descriptor, class_loader, *pair.first, *pair.second);
2197 } else {
2198 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2199 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2200 self->SetException(ThrowLocation(), pre_allocated);
2201 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002202 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002203 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002204 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002205 mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, class_loader);
2206 if (klass != nullptr) {
2207 return klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002208 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002209 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002210 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002211 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002212 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002213 {
2214 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002215 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2216 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002217 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002218 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002219 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002220 }
Ian Rogers68b56852014-08-29 20:19:11 -07002221 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002222 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2223 WellKnownClasses::java_lang_ClassLoader_loadClass,
2224 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002225 }
Ian Rogers98379392014-02-24 16:53:16 -08002226 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002227 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002228 return nullptr;
2229 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002230 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002231 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002232 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002233 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002234 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002235 // success, return mirror::Class*
2236 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002237 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002238 }
Ian Rogers07140832014-09-30 15:43:59 -07002239 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002240}
2241
Ian Rogers7b078e82014-09-10 14:44:24 -07002242mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002243 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002244 const DexFile& dex_file,
2245 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002246 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002247 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002248 bool should_allocate = false;
2249
Brian Carlstromaded5f72011-10-07 17:15:04 -07002250 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002251 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002252 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002253 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002254 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002255 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002256 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002257 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002258 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002259 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2260 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002261 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002262 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002263 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002264 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002265 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002266 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002267 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002268 should_allocate = true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002269 }
2270 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002271 should_allocate = true;
2272 }
2273
2274 if (should_allocate) {
2275 // Allocate a class with the status of not ready.
2276 // Interface object should get the right size here. Regular class will
2277 // figure out the right size later and be replaced with one of the right
2278 // size when the class becomes resolved.
2279 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002280 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002281 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002282 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002283 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002284 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002285 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002286 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002287 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002288 if (self->IsExceptionPending()) {
2289 // An exception occured during load, set status to erroneous while holding klass' lock in case
2290 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002291 if (!klass->IsErroneous()) {
2292 klass->SetStatus(mirror::Class::kStatusError, self);
2293 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002294 return nullptr;
2295 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002296 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002297
Mathieu Chartier590fee92013-09-13 13:46:47 -07002298 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002299 mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
Ian Rogersc114b5f2014-07-21 08:55:01 -07002300 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002301 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2302 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002303 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002304 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002305
Brian Carlstromaded5f72011-10-07 17:15:04 -07002306 // Finish loading (if necessary) by finding parents
2307 CHECK(!klass->IsLoaded());
2308 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2309 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002310 if (!klass->IsErroneous()) {
2311 klass->SetStatus(mirror::Class::kStatusError, self);
2312 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002313 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002314 }
2315 CHECK(klass->IsLoaded());
2316 // Link the class (if necessary)
2317 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002318 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002319 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002320
2321 mirror::Class* new_class = nullptr;
2322 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002323 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002324 if (!klass->IsErroneous()) {
2325 klass->SetStatus(mirror::Class::kStatusError, self);
2326 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002327 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002328 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002329 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002330 CHECK(new_class != nullptr) << descriptor;
2331 CHECK(new_class->IsResolved()) << descriptor;
2332
2333 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002334
2335 /*
2336 * We send CLASS_PREPARE events to the debugger from here. The
2337 * definition of "preparation" is creating the static fields for a
2338 * class and initializing them to the standard default values, but not
2339 * executing any code (that comes later, during "initialization").
2340 *
2341 * We did the static preparation in LinkClass.
2342 *
2343 * The class has been prepared and resolved but possibly not yet verified
2344 * at this point.
2345 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002346 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002347
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002348 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002349}
2350
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002351uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2352 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002353 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002354 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002355 size_t num_8 = 0;
2356 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002357 size_t num_32 = 0;
2358 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002359 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002360 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2361 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002362 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002363 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002364 switch (c) {
2365 case 'L':
2366 case '[':
2367 num_ref++;
2368 break;
2369 case 'J':
2370 case 'D':
2371 num_64++;
2372 break;
2373 case 'I':
2374 case 'F':
2375 num_32++;
2376 break;
2377 case 'S':
2378 case 'C':
2379 num_16++;
2380 break;
2381 case 'B':
2382 case 'Z':
2383 num_8++;
2384 break;
2385 default:
2386 LOG(FATAL) << "Unknown descriptor: " << c;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002387 }
2388 }
2389 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002390 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002391}
2392
Ian Rogers97b52f82014-08-14 11:34:07 -07002393OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2394 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002395 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002396 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2397 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002398 *found = false;
2399 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002400 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002401 *found = true;
2402 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002403}
2404
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002405static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2406 uint32_t method_idx) {
2407 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002408 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002409 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002410 ClassDataItemIterator it(dex_file, class_data);
2411 // Skip fields
2412 while (it.HasNextStaticField()) {
2413 it.Next();
2414 }
2415 while (it.HasNextInstanceField()) {
2416 it.Next();
2417 }
2418 // Process methods
2419 size_t class_def_method_index = 0;
2420 while (it.HasNextDirectMethod()) {
2421 if (it.GetMemberIndex() == method_idx) {
2422 return class_def_method_index;
2423 }
2424 class_def_method_index++;
2425 it.Next();
2426 }
2427 while (it.HasNextVirtualMethod()) {
2428 if (it.GetMemberIndex() == method_idx) {
2429 return class_def_method_index;
2430 }
2431 class_def_method_index++;
2432 it.Next();
2433 }
2434 DCHECK(!it.HasNext());
2435 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2436 return 0;
2437}
2438
Ian Rogers97b52f82014-08-14 11:34:07 -07002439const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002440 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002441 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002442 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002443 size_t oat_method_index;
2444 if (method->IsStatic() || method->IsDirect()) {
2445 // Simple case where the oat method index was stashed at load time.
2446 oat_method_index = method->GetMethodIndex();
2447 } else {
2448 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2449 // by search for its position in the declared virtual methods.
2450 oat_method_index = declaring_class->NumDirectMethods();
2451 size_t end = declaring_class->NumVirtualMethods();
2452 bool found = false;
2453 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002454 // Check method index instead of identity in case of duplicate method definitions.
2455 if (method->GetDexMethodIndex() ==
2456 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Ian Rogersfb6adba2012-03-04 21:51:51 -08002457 found = true;
2458 break;
2459 }
Ian Rogersf320b632012-03-13 18:47:47 -07002460 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002461 }
2462 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2463 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002464 DCHECK_EQ(oat_method_index,
2465 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002466 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002467 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002468 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2469 declaring_class->GetDexClassDefIndex(),
2470 found);
2471 if (!found) {
2472 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002473 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002474 *found = true;
2475 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002476}
2477
2478// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002479const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002480 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002481 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002482 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002483 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002484 bool found;
2485 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002486 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002487 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002488 result = oat_method.GetQuickCode();
2489 }
2490
Ian Rogersef7d42f2014-01-06 12:55:46 -08002491 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002492 if (method->IsNative()) {
2493 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002494 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002495 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002496 // No code? Do we expect portable code?
2497 result = GetQuickToPortableBridge();
2498 } else {
2499 // No code? You must mean to go into the interpreter.
2500 result = GetQuickToInterpreterBridge();
2501 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002502 }
2503 return result;
TDYa12785321912012-04-01 15:24:56 -07002504}
2505
Ian Rogersef7d42f2014-01-06 12:55:46 -08002506const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2507 bool* have_portable_code) {
2508 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2509 *have_portable_code = false;
2510 if (method->IsProxyMethod()) {
2511 return GetPortableProxyInvokeHandler();
2512 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002513 bool found;
2514 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002515 const void* result = nullptr;
2516 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002517 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002518 result = oat_method.GetPortableCode();
2519 quick_code = oat_method.GetQuickCode();
2520 }
2521
Ian Rogersef7d42f2014-01-06 12:55:46 -08002522 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002523 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002524 // No code? You must mean to go into the interpreter.
2525 result = GetPortableToInterpreterBridge();
2526 } else {
2527 // No code? But there's quick code, so use a bridge.
2528 result = GetPortableToQuickBridge();
2529 }
2530 } else {
2531 *have_portable_code = true;
2532 }
2533 return result;
2534}
2535
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002536const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2537 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2538 return nullptr;
2539 }
2540 bool found;
2541 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2542 return found ? oat_method.GetQuickCode() : nullptr;
2543}
2544
2545const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2546 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2547 return nullptr;
2548 }
2549 bool found;
2550 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2551 return found ? oat_method.GetPortableCode() : nullptr;
2552}
2553
Ian Rogersef7d42f2014-01-06 12:55:46 -08002554const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2555 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002556 bool found;
2557 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2558 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002559 return nullptr;
2560 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002561 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002562 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002563}
2564
2565const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2566 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002567 bool found;
2568 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2569 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002570 return nullptr;
2571 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002572 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002573 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002574}
2575
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002576// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002577static bool NeedsInterpreter(
2578 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2579 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002580 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002581 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002582 // May return true for native code, in the case of generic JNI
2583 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002584 return true;
2585 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002586#ifdef ART_SEA_IR_MODE
2587 ScopedObjectAccess soa(Thread::Current());
2588 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2589 LOG(INFO) << "Found " << PrettyMethod(method);
2590 return false;
2591 }
2592#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002593 // If interpreter mode is enabled, every method (except native and proxy) must
2594 // be run with interpreter.
2595 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2596 !method->IsNative() && !method->IsProxyMethod();
2597}
2598
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002599void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002600 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002601 if (klass->NumDirectMethods() == 0) {
2602 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002603 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002604 Runtime* runtime = Runtime::Current();
2605 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002606 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2607 return; // OAT file unavailable.
2608 }
Ian Rogers19846512012-02-24 11:42:47 -08002609 }
Alex Light64ad14d2014-08-19 14:23:13 -07002610
Mathieu Chartierf8322842014-05-16 10:59:25 -07002611 const DexFile& dex_file = klass->GetDexFile();
2612 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002613 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002614 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002615 // There should always be class data if there were direct methods.
2616 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002617 ClassDataItemIterator it(dex_file, class_data);
2618 // Skip fields
2619 while (it.HasNextStaticField()) {
2620 it.Next();
2621 }
2622 while (it.HasNextInstanceField()) {
2623 it.Next();
2624 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002625 bool has_oat_class;
2626 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2627 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002628 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002629 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002630 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002631 if (!method->IsStatic()) {
2632 // Only update static methods.
2633 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002634 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002635 const void* portable_code = nullptr;
2636 const void* quick_code = nullptr;
2637 if (has_oat_class) {
2638 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2639 portable_code = oat_method.GetPortableCode();
2640 quick_code = oat_method.GetQuickCode();
2641 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002642 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2643 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002644 if (enter_interpreter) {
2645 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002646 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002647 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002648 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002649 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002650 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002651 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002652 quick_code = GetQuickToInterpreterBridge();
2653 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002654 } else {
2655 if (portable_code == nullptr) {
2656 portable_code = GetPortableToQuickBridge();
2657 } else {
2658 have_portable_code = true;
2659 }
2660 if (quick_code == nullptr) {
2661 quick_code = GetQuickToPortableBridge();
2662 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002663 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002664 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2665 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002666 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002667 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002668}
2669
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002670void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002671 const OatFile::OatClass* oat_class,
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +07002672 const DexFile& dex_file, uint32_t dex_method_index,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07002673 uint32_t method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002674 Runtime* runtime = Runtime::Current();
2675 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002676 // The following code only applies to a non-compiler runtime.
2677 return;
2678 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002679 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002680 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2681 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002682 if (oat_class != nullptr) {
2683 // Every kind of method should at least get an invoke stub from the oat_method.
2684 // non-abstract methods also get their code pointers.
2685 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2686 oat_method.LinkMethod(method.Get());
2687 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002688
Jeff Hao16743632013-05-08 10:59:04 -07002689 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002690 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002691 method->GetEntryPointFromQuickCompiledCode(),
2692 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002693 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002694 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002695 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002696 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002697 }
2698
Brian Carlstrom92827a52011-10-10 15:50:01 -07002699 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002700 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2701 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002702 return;
2703 }
Ian Rogers19846512012-02-24 11:42:47 -08002704
Ian Rogersef7d42f2014-01-06 12:55:46 -08002705 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002706 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002707 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002708 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2709 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002710 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2711 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002712 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002713 if (!method->IsNative()) {
2714 // Set entry point from compiled code if there's no code or in interpreter only mode.
2715 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2716 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2717 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002718 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002719 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2720 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002721 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2722 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2723 have_portable_code = true;
2724 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2725 } else {
2726 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2727 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002728 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002729
Ian Rogers62d6c772013-02-27 08:32:07 -08002730 if (method->IsNative()) {
2731 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002732 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002733
2734 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002735 // We have a native method here without code. Then it should have either the generic JNI
2736 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2737 // TODO: this doesn't handle all the cases where trampolines may be installed.
2738 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2739 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002740 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002741 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002742
Ian Rogers62d6c772013-02-27 08:32:07 -08002743 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002744 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002745 method->GetEntryPointFromQuickCompiledCode(),
2746 method->GetEntryPointFromPortableCompiledCode(),
2747 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002748}
2749
Fred Shih37f05ef2014-07-16 18:38:08 -07002750
Fred Shih37f05ef2014-07-16 18:38:08 -07002751
Ian Rogers7b078e82014-09-10 14:44:24 -07002752void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002753 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002754 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002755 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002756 CHECK(klass.Get() != nullptr);
2757 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002758 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002759 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002760 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002761
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002762 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002763 if (kUseBakerOrBrooksReadBarrier) {
2764 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002765 }
Andreas Gampe51829322014-08-25 15:05:04 -07002766 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002767 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002768 klass->SetAccessFlags(access_flags);
2769 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002770 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002771 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002772
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002773 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002774 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002775
Ian Rogers13735952014-10-08 12:43:28 -07002776 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002777 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002778 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002779 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002780
Ian Rogers97b52f82014-08-14 11:34:07 -07002781
2782 bool has_oat_class = false;
2783 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2784 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2785 &has_oat_class);
2786 if (has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002787 LoadClassMembers(self, dex_file, class_data, klass, class_loader, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002788 }
2789 }
2790 if (!has_oat_class) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002791 LoadClassMembers(self, dex_file, class_data, klass, class_loader, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002792 }
2793}
2794
Ian Rogers7b078e82014-09-10 14:44:24 -07002795void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002796 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002797 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002798 mirror::ClassLoader* class_loader,
2799 const OatFile::OatClass* oat_class) {
2800 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002801 ClassDataItemIterator it(dex_file, class_data);
2802 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002803 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002804 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002805 CHECK(self->IsExceptionPending()); // OOME.
2806 return;
2807 }
2808 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002809 }
2810 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002811 mirror::ObjectArray<mirror::ArtField>* fields =
2812 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002813 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002814 CHECK(self->IsExceptionPending()); // OOME.
2815 return;
2816 }
2817 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002818 }
2819 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002820 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002821 StackHandleScope<1> hs(self);
2822 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002823 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002824 CHECK(self->IsExceptionPending()); // OOME.
2825 return;
2826 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002827 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002828 LoadField(dex_file, it, klass, sfield);
2829 }
2830 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002831 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002832 StackHandleScope<1> hs(self);
2833 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002834 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002835 CHECK(self->IsExceptionPending()); // OOME.
2836 return;
2837 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002838 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002839 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002840 }
2841
Ian Rogers0571d352011-11-03 19:51:38 -07002842 // Load methods.
2843 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002844 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002845 mirror::ObjectArray<mirror::ArtMethod>* directs =
2846 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002847 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002848 CHECK(self->IsExceptionPending()); // OOME.
2849 return;
2850 }
2851 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002852 }
Ian Rogers0571d352011-11-03 19:51:38 -07002853 if (it.NumVirtualMethods() != 0) {
2854 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002855 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2856 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002857 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002858 CHECK(self->IsExceptionPending()); // OOME.
2859 return;
2860 }
2861 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002862 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002863 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002864 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2865 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002866 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002867 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002868 StackHandleScope<1> hs(self);
2869 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002870 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002871 CHECK(self->IsExceptionPending()); // OOME.
2872 return;
2873 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002874 klass->SetDirectMethod(i, method.Get());
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002875 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002876 uint32_t it_method_index = it.GetMemberIndex();
2877 if (last_dex_method_index == it_method_index) {
2878 // duplicate case
2879 method->SetMethodIndex(last_class_def_method_index);
2880 } else {
2881 method->SetMethodIndex(class_def_method_index);
2882 last_dex_method_index = it_method_index;
2883 last_class_def_method_index = class_def_method_index;
2884 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002885 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002886 }
2887 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002888 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002889 StackHandleScope<1> hs(self);
2890 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002891 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002892 CHECK(self->IsExceptionPending()); // OOME.
2893 return;
2894 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002895 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002896 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002897 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002898 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002899 }
2900 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002901}
2902
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002903void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002904 Handle<mirror::Class> klass,
2905 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002906 uint32_t field_idx = it.GetMemberIndex();
2907 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002908 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002909 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002910}
2911
Brian Carlstromea46f952013-07-30 01:26:50 -07002912mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002913 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002914 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002915 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002916 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002917 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002918
Brian Carlstromea46f952013-07-30 01:26:50 -07002919 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002920 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002921 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002922 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002923 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002924 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002925
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002926 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002927 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002928 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002929 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002930
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002931 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
Ian Rogers19846512012-02-24 11:42:47 -08002932 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002933 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002934
Andreas Gampe51829322014-08-25 15:05:04 -07002935 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002936
Ian Rogersdfb325e2013-10-30 01:00:44 -07002937 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002938 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002939 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2940 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002941 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002942 klass->SetFinalizable();
2943 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002944 std::string temp;
2945 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002946 // The Enum class declares a "final" finalize() method to prevent subclasses from
2947 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2948 // subclasses, so we exclude it here.
2949 // We also want to avoid setting the flag on Object, where we know that finalize() is
2950 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002951 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2952 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002953 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002954 }
2955 }
2956 }
2957 } else if (method_name[0] == '<') {
2958 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002959 bool is_init = (strcmp("<init>", method_name) == 0);
2960 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002961 if (UNLIKELY(!is_init && !is_clinit)) {
2962 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2963 } else {
2964 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2965 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002966 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002967 access_flags |= kAccConstructor;
2968 }
2969 }
2970 }
2971 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002972
Mathieu Chartier66f19252012-09-18 08:57:04 -07002973 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002974}
2975
Ian Rogers7b078e82014-09-10 14:44:24 -07002976void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002977 StackHandleScope<1> hs(self);
2978 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002979 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2980 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002981 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002982}
2983
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002984void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002985 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002986 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002987 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002988 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002989}
2990
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002991bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002992 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002993 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002994 mirror::DexCache* dex_cache = GetDexCache(i);
2995 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002996 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002997 }
2998 }
2999 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003000}
3001
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003002bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003003 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003004 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003005}
3006
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003007void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003008 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003009 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003010 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003011 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3012 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003013 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003014 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003015 if (log_new_dex_caches_roots_) {
3016 // TODO: This is not safe if we can remove dex caches.
3017 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3018 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003019}
3020
Brian Carlstromaded5f72011-10-07 17:15:04 -07003021void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003022 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003023 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003024 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003025 if (IsDexFileRegisteredLocked(dex_file)) {
3026 return;
3027 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003028 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003029 // Don't alloc while holding the lock, since allocation may need to
3030 // suspend all threads and another thread may need the dex_lock_ to
3031 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003032 StackHandleScope<1> hs(self);
3033 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003034 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3035 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003036 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003037 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003038 if (IsDexFileRegisteredLocked(dex_file)) {
3039 return;
3040 }
3041 RegisterDexFileLocked(dex_file, dex_cache);
3042 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003043}
3044
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003045void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003046 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003047 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003048 RegisterDexFileLocked(dex_file, dex_cache);
3049}
3050
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003051mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003052 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003053 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003054 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003055 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003056 if (dex_cache->GetDexFile() == &dex_file) {
3057 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003058 }
3059 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003060 // Search matching by location name.
3061 std::string location(dex_file.GetLocation());
3062 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003063 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003064 if (dex_cache->GetDexFile()->GetLocation() == location) {
3065 return dex_cache;
3066 }
3067 }
3068 // Failure, dump diagnostic and abort.
3069 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003070 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003071 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3072 }
3073 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003074 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003075}
3076
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003077void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003078 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003079 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003080 mirror::DexCache* dex_cache = GetDexCache(i);
3081 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003082 }
3083}
3084
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003085mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003086 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003087 if (UNLIKELY(klass == nullptr)) {
3088 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003089 }
3090 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003091}
3092
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003093mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3094 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003095 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003096 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003097 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003098 StackHandleScope<1> hs(self);
3099 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003100 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003101 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003102 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003103 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3104 const char* descriptor = Primitive::Descriptor(type);
3105 mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003106 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003107 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003108}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003109
Brian Carlstrombe977852011-07-19 14:54:54 -07003110// Create an array class (i.e. the class object for the array, not the
3111// array itself). "descriptor" looks like "[C" or "[[[[B" or
3112// "[Ljava/lang/String;".
3113//
3114// If "descriptor" refers to an array of primitives, look up the
3115// primitive type's internally-generated class object.
3116//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003117// "class_loader" is the class loader of the class that's referring to
3118// us. It's used to ensure that we're looking for the element type in
3119// the right context. It does NOT become the class loader for the
3120// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003121//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003122// Returns nullptr with an exception raised on failure.
Ian Rogers98379392014-02-24 16:53:16 -08003123mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003124 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003125 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003126 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003127 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003128 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3129 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003130 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003131 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003132 // We need to accept erroneous classes as component types.
Ian Rogers7b078e82014-09-10 14:44:24 -07003133 component_type.Assign(LookupClass(self, descriptor + 1, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003134 if (component_type.Get() == nullptr) {
3135 DCHECK(self->IsExceptionPending());
3136 return nullptr;
3137 } else {
3138 self->ClearException();
3139 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003140 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003141 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3142 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3143 return nullptr;
3144 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003145 // See if the component type is already loaded. Array classes are
3146 // always associated with the class loader of their underlying
3147 // element type -- an array of Strings goes with the loader for
3148 // java/lang/String -- so we need to look for it there. (The
3149 // caller should have checked for the existence of the class
3150 // before calling here, but they did so with *their* class loader,
3151 // not the component type's loader.)
3152 //
3153 // If we find it, the caller adds "loader" to the class' initiating
3154 // loader list, which should prevent us from going through this again.
3155 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003156 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003157 // are the same, because our caller (FindClass) just did the
3158 // lookup. (Even if we get this wrong we still have correct behavior,
3159 // because we effectively do this lookup again when we add the new
3160 // class to the hash table --- necessary because of possible races with
3161 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003162 if (class_loader.Get() != component_type->GetClassLoader()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003163 mirror::Class* new_class = LookupClass(self, descriptor, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003164 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003165 return new_class;
3166 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003167 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003168
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003169 // Fill out the fields in the Class.
3170 //
3171 // It is possible to execute some methods against arrays, because
3172 // all arrays are subclasses of java_lang_Object_, so we need to set
3173 // up a vtable. We can just point at the one in java_lang_Object_.
3174 //
3175 // Array classes are simple enough that we don't need to do a full
3176 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003177 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003178 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003179 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003180 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003181 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003182 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003183 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003184 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003185 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003186 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003187 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003188 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003189 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003190 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003191 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003192 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003193 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003194 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003195 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003196 }
3197 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003198 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003199 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003200 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003201 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003202 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003203 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003204 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003205 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003206 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003207 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003208 new_class->SetSuperClass(java_lang_Object);
3209 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003210 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003211 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003212 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
3213 new_class->PopulateEmbeddedImtAndVTable();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003214 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003215 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003216 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003217
3218
3219 // All arrays have java/lang/Cloneable and java/io/Serializable as
3220 // interfaces. We need to set that up here, so that stuff like
3221 // "instanceof" works right.
3222 //
3223 // Note: The GC could run during the call to FindSystemClass,
3224 // so we need to make sure the class object is GC-valid while we're in
3225 // there. Do this by clearing the interface list so the GC will just
3226 // think that the entries are null.
3227
3228
3229 // Use the single, global copies of "interfaces" and "iftable"
3230 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003231 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003232 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003233 CHECK(array_iftable != nullptr);
3234 new_class->SetIfTable(array_iftable);
3235 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003236
Elliott Hughes00626c22013-06-14 15:04:14 -07003237 // Inherit access flags from the component type.
3238 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3239 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3240 access_flags &= kAccJavaFlagsMask;
3241 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003242 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003243 access_flags |= kAccAbstract | kAccFinal;
3244 access_flags &= ~kAccInterface;
3245
3246 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003247
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003248 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003249 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003250 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003251 }
3252 // Another thread must have loaded the class after we
3253 // started but before we finished. Abandon what we've
3254 // done.
3255 //
3256 // (Yes, this happens.)
3257
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003258 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003259}
3260
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003261mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003262 switch (type) {
3263 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003264 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003265 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003266 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003267 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003268 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003269 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003270 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003271 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003272 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003273 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003274 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003275 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003276 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003277 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003278 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003279 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003280 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003281 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003282 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003283 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003284 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003285 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003286 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003287}
3288
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003289mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3290 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003291 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003292 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003293 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003294 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003295 source += " from ";
3296 source += dex_cache->GetLocation()->ToModifiedUtf8();
3297 }
3298 LOG(INFO) << "Loaded class " << descriptor << source;
3299 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003300 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers1d54e732013-05-02 21:10:01 -07003301 mirror::Class* existing =
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003302 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003303 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003304 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003305 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003306 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003307 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003308 // Check a class loaded with the system class loader matches one in the image if the class
3309 // is in the image.
3310 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003311 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003312 CHECK(klass == existing);
3313 }
3314 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003315 VerifyObject(klass);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003316 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003317 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003318 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003319 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003320 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003321}
3322
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003323mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3324 size_t hash) {
3325 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3326 mirror::Class* existing =
3327 LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3328
3329 if (existing == nullptr) {
3330 CHECK(klass->IsProxyClass());
3331 return nullptr;
3332 }
3333
3334 CHECK_NE(existing, klass) << descriptor;
3335 CHECK(!existing->IsResolved()) << descriptor;
3336 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3337
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003338 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3339 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003340 mirror::Class* klass = it->second.Read();
Hiroshi Yamauchi0fbd6e62014-07-17 16:16:31 -07003341 if (klass == existing) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003342 class_table_.erase(it);
3343 break;
3344 }
3345 }
3346
3347 CHECK(!klass->IsTemp()) << descriptor;
3348 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3349 dex_cache_image_class_lookup_required_) {
3350 // Check a class loaded with the system class loader matches one in the image if the class
3351 // is in the image.
3352 existing = LookupClassFromImage(descriptor);
3353 if (existing != nullptr) {
3354 CHECK(klass == existing) << descriptor;
3355 }
3356 }
3357 VerifyObject(klass);
3358
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003359 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003360 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003361 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003362 }
3363
3364 return existing;
3365}
3366
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003367bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003368 size_t hash = Hash(descriptor);
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003369 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Brian Carlstromf3632832014-05-20 15:36:53 -07003370 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3371 it != end && it->first == hash;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003372 ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003373 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003374 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003375 class_table_.erase(it);
Brian Carlstromae826982011-11-09 01:33:42 -08003376 return true;
3377 }
3378 }
3379 return false;
3380}
3381
Ian Rogers7b078e82014-09-10 14:44:24 -07003382mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003383 const mirror::ClassLoader* class_loader) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08003384 size_t hash = Hash(descriptor);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003385 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003386 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003387 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003388 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003389 return result;
3390 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003391 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003392 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3393 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003394 } else {
3395 // Lookup failed but need to search dex_caches_.
3396 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003397 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003398 InsertClass(descriptor, result, hash);
3399 } else {
3400 // Searching the image dex files/caches failed, we don't want to get into this situation
3401 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3402 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003403 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003404 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3405 MoveImageClassesToClassTable();
3406 }
3407 }
3408 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003409 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003410}
3411
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003412mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3413 const mirror::ClassLoader* class_loader,
3414 size_t hash) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003415 auto end = class_table_.end();
3416 for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003417 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003418 if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003419 if (kIsDebugBuild) {
3420 // Check for duplicates in the table.
3421 for (++it; it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003422 mirror::Class* klass2 = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003423 CHECK(!(klass2->GetClassLoader() == class_loader &&
3424 klass2->DescriptorEquals(descriptor)))
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003425 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3426 << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003427 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003428 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003429 return klass;
3430 }
3431 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003432 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003433}
3434
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003435static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3436 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3437 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003438 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003439 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3440 return root->AsObjectArray<mirror::DexCache>();
3441}
3442
3443void ClassLinker::MoveImageClassesToClassTable() {
3444 Thread* self = Thread::Current();
3445 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3446 if (!dex_cache_image_class_lookup_required_) {
3447 return; // All dex cache classes are already in the class table.
3448 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003449 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003450 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003451 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003452 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3453 mirror::DexCache* dex_cache = dex_caches->Get(i);
3454 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3455 for (int32_t j = 0; j < types->GetLength(); j++) {
3456 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003457 if (klass != nullptr) {
3458 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003459 const char* descriptor = klass->GetDescriptor(&temp);
3460 size_t hash = Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003461 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3462 if (existing != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003463 CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3464 << PrettyClassAndClassLoader(klass);
3465 } else {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003466 class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003467 if (log_new_class_table_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003468 new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003469 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003470 }
3471 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003472 }
3473 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003474 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003475}
3476
3477mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003478 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003479 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3480 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3481 mirror::DexCache* dex_cache = dex_caches->Get(i);
3482 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003483 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003484 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003485 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003486 const DexFile::TypeId* type_id =
3487 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003488 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003489 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3490 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003491 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003492 return klass;
3493 }
3494 }
3495 }
3496 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003497 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003498}
3499
3500void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3501 result.clear();
3502 if (dex_cache_image_class_lookup_required_) {
3503 MoveImageClassesToClassTable();
3504 }
3505 size_t hash = Hash(descriptor);
3506 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003507 for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
Mathieu Chartier02e25112013-08-14 16:14:24 -07003508 it != end && it->first == hash; ++it) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003509 mirror::Class* klass = it->second.Read();
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003510 if (klass->DescriptorEquals(descriptor)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003511 result.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003512 }
3513 }
3514}
3515
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003516void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003517 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003518 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003519
Ian Rogers9ffb0392012-09-10 11:56:50 -07003520 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003521 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003522 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003523 return;
3524 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003525 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3526 return;
3527 }
jeffhao98eacac2011-09-14 16:11:53 -07003528
Ian Rogers9ffb0392012-09-10 11:56:50 -07003529 // The class might already be erroneous, for example at compile time if we attempted to verify
3530 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003531 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003532 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003533 return;
3534 }
3535
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003536 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003537 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003538 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003539 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003540 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003541 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003542 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003543 }
jeffhao98eacac2011-09-14 16:11:53 -07003544
Jeff Hao4a200f52014-04-01 14:58:49 -07003545 // Skip verification if disabled.
3546 if (!Runtime::Current()->IsVerificationEnabled()) {
3547 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003548 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003549 return;
3550 }
3551
Ian Rogers9ffb0392012-09-10 11:56:50 -07003552 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003553 StackHandleScope<2> hs(self);
3554 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003555 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003556 // Acquire lock to prevent races on verifying the super class.
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003557 ObjectLock<mirror::Class> lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003558
3559 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003560 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003561 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003562 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003563 std::string error_msg(
3564 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3565 PrettyDescriptor(klass.Get()).c_str(),
3566 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003567 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003568 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3569 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003570 self->ClearException();
3571 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003572 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3573 if (cause.Get() != nullptr) {
3574 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003575 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003576 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003577 if (Runtime::Current()->IsCompiler()) {
3578 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3579 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003580 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003581 return;
3582 }
3583 }
3584
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003585 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003586 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003587 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003588 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003589 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003590 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003591 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003592 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003593 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3594 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003595 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003596 return;
3597 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003598 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003599 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003600 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003601 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003602 Runtime::Current()->IsCompiler(),
3603 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003604 }
3605 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003606 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003607 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003608 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3609 << " because: " << error_msg;
3610 }
Ian Rogers1f539342012-10-03 21:09:42 -07003611 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003612 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003613 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003614 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003615 // Even though there were no verifier failures we need to respect whether the super-class
3616 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003617 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003618 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003619 } else {
3620 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003621 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003622 // Pretend a soft failure occured so that we don't consider the class verified below.
3623 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003624 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003625 } else {
3626 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3627 // Soft failures at compile time should be retried at runtime. Soft
3628 // failures at runtime will be handled by slow paths in the generated
3629 // code. Set status accordingly.
3630 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003631 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003632 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003633 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003634 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3635 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003636 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003637 }
3638 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003639 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003640 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003641 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3642 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003643 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003644 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003645 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003646 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003647 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003648 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003649 // Let the interpreter know it by setting the kAccPreverified flag onto each
3650 // method.
3651 // Note: we're going here during compilation and at runtime. When we set the
3652 // kAccPreverified flag when compiling image classes, the flag is recorded
3653 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003654 EnsurePreverifiedMethods(klass);
3655 }
3656}
3657
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003658void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003659 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003660 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003661 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003662 }
jeffhao98eacac2011-09-14 16:11:53 -07003663}
3664
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003665bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3666 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003667 // If we're compiling, we can only verify the class using the oat file if
3668 // we are not compiling the image or if the class we're verifying is not part of
3669 // the app. In other words, we will only check for preverification of bootclasspath
3670 // classes.
3671 if (Runtime::Current()->IsCompiler()) {
3672 // Are we compiling the bootclasspath?
3673 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3674 return false;
3675 }
3676 // We are compiling an app (not the image).
3677
3678 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003679 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003680 return false;
3681 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003682 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003683
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003684 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003685 // In case we run without an image there won't be a backing oat file.
3686 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003687 return false;
3688 }
3689
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003690 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003691 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003692 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3693 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003694 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003695 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003696 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003697 // Compile time verification failed with a soft error. Compile time verification can fail
3698 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003699 // class ... {
3700 // Foo x;
3701 // .... () {
3702 // if (...) {
3703 // v1 gets assigned a type of resolved class Foo
3704 // } else {
3705 // v1 gets assigned a type of unresolved class Bar
3706 // }
3707 // iput x = v1
3708 // } }
3709 // when we merge v1 following the if-the-else it results in Conflict
3710 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3711 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3712 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3713 // at compile time).
3714 return false;
3715 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003716 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003717 // Compile time verification failed with a hard error. This is caused by invalid instructions
3718 // in the class. These errors are unrecoverable.
3719 return false;
3720 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003721 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003722 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3723 // not loading the class.
3724 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3725 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003726 return false;
3727 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003728 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003729 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003730 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003731 << klass->GetDescriptor(&temp);
Brian Carlstrom5b332c82012-02-01 15:02:31 -08003732
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003733 return false;
3734}
3735
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003736void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003737 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003738 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3739 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3740 }
3741 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3742 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3743 }
3744}
3745
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003746void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003747 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003748 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3749 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003750 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003751 return; // native or abstract method
3752 }
3753 if (code_item->tries_size_ == 0) {
3754 return; // nothing to process
3755 }
Ian Rogers13735952014-10-08 12:43:28 -07003756 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003757 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3758 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3759 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3760 CatchHandlerIterator iterator(handlers_ptr);
3761 for (; iterator.HasNext(); iterator.Next()) {
3762 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3763 // unresolved exception types will be ignored by exception delivery
3764 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003765 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003766 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003767 DCHECK(Thread::Current()->IsExceptionPending());
3768 Thread::Current()->ClearException();
3769 }
3770 }
3771 }
3772 handlers_ptr = iterator.EndDataPointer();
3773 }
3774}
3775
Brian Carlstromea46f952013-07-30 01:26:50 -07003776static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003777static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3778 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003779
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003780mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003781 jobjectArray interfaces, jobject loader,
3782 jobjectArray methods, jobjectArray throws) {
3783 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003784 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003785 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003786 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003787 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003788 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003789 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003790 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003791 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003792 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003793 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3794 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003795 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003796 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003797 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003798 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003799 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003800 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003801
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003802 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003803 {
3804 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003805 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003806 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003807 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003808 }
3809 klass->SetSFields(sfields);
3810 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003811 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3812 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003813 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3814 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003815 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003816 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003817 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003818 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003819 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003820 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003821 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3822 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003823 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3824 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003825 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003826 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003827 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003828 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003829 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003830 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003831 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003832
Ian Rogers466bb252011-10-14 03:29:56 -07003833 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003834 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003835 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003836 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003837 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003838 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003839 }
3840 klass->SetDirectMethods(directs);
3841 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003842 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003843 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003844 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003845 }
3846 klass->SetDirectMethod(0, constructor);
3847 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003848
Mathieu Chartier590fee92013-09-13 13:46:47 -07003849 // Create virtual method using specified prototypes.
3850 size_t num_virtual_methods =
3851 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003852 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003853 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3854 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003855 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003856 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003857 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003858 }
3859 klass->SetVirtualMethods(virtuals);
3860 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003861 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003862 StackHandleScope<1> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003863 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3864 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003865 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003866 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003867 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003868 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003869 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003870 }
3871 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003872 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003873
3874 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003875 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003876 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003877
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003878 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3879 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003880 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003881 // Must hold lock on object when resolved.
3882 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003883 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003884 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003885 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003886 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003887 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003888 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003889 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003890 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003891
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003892 CHECK(klass->IsRetired());
3893 CHECK_NE(klass.Get(), new_class);
3894 klass.Assign(new_class);
3895
3896 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003897 interfaces_sfield->SetObject<false>(klass.Get(),
3898 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003899 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003900 throws_sfield->SetObject<false>(klass.Get(),
3901 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003902
3903 {
3904 // Lock on klass is released. Lock new class object.
3905 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003906 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003907 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003908
3909 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003910 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003911 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003912 CheckProxyConstructor(klass->GetDirectMethod(0));
3913 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003914 StackHandleScope<2> hs(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003915 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3916 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003917 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003918 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3919 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003920 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003921
Mathieu Chartier590fee92013-09-13 13:46:47 -07003922 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003923 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003924 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003925 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3926
3927 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003928 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003929 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003930
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003931 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003932 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003933 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003934 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003935 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003936 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003937 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003938 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003939}
3940
Ian Rogersef7d42f2014-01-06 12:55:46 -08003941std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003942 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003943 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003944 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003945 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3946}
3947
Ian Rogersef7d42f2014-01-06 12:55:46 -08003948mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3949 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003950 DCHECK(proxy_class->IsProxyClass());
3951 DCHECK(proxy_method->IsProxyMethod());
3952 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003953 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003954 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003955 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003956 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003957 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003958 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003959 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003960 break;
3961 }
3962 }
3963 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003964 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003965 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003966 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003967 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003968 return resolved_method;
3969}
3970
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003971
Brian Carlstromea46f952013-07-30 01:26:50 -07003972mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003973 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003974 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003975 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003976 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003977 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003978 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3979 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003980 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3981 // constructor method.
3982 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3983 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003984 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3985 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003986 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3987 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003988 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003989 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003990 }
Ian Rogers466bb252011-10-14 03:29:56 -07003991 // Make this constructor public and fix the class to be our Proxy version
3992 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003993 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003994 return constructor;
3995}
3996
Brian Carlstromea46f952013-07-30 01:26:50 -07003997static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003998 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003999 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004000 CHECK_STREQ(constructor->GetName(), "<init>");
4001 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4002 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004003 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004004}
4005
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004006mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004007 Handle<mirror::Class> klass,
4008 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004009 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4010 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004011 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004012 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004013 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004014 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004015 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004016 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004017 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004018 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004019 }
Ian Rogers466bb252011-10-14 03:29:56 -07004020
4021 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4022 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004023 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004024 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004025
Ian Rogers466bb252011-10-14 03:29:56 -07004026 // At runtime the method looks like a reference and argument saving method, clone the code
4027 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004028 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4029 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004030 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004031
Ian Rogersc2b44472011-12-14 21:17:17 -08004032 return method;
4033}
Jesse Wilson95caa792011-10-12 18:14:17 -04004034
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004035static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4036 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004037 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004038 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004039 CHECK(!prototype->IsFinal());
4040 CHECK(method->IsFinal());
4041 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004042
4043 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4044 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4045 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
Andreas Gampe58a5af82014-07-31 16:23:49 -07004046 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4047 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004048 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4049
Mathieu Chartierbf99f772014-08-23 16:37:27 -07004050 StackHandleScope<2> hs(Thread::Current());
4051 MethodHelper mh(hs.NewHandle(method.Get()));
4052 MethodHelper mh2(hs.NewHandle(prototype.Get()));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004053 CHECK_STREQ(method->GetName(), prototype->GetName());
4054 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004055 // More complex sanity - via dex cache
Ian Rogers19846512012-02-24 11:42:47 -08004056 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004057}
4058
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004059static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4060 bool can_init_parents)
4061 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004062 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004063 return true;
4064 }
4065 if (!can_init_statics) {
4066 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004067 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004068 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004069 return false;
4070 }
4071 // Check if there are encoded static values needing initialization.
4072 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004073 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004074 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004075 if (dex_class_def->static_values_off_ != 0) {
4076 return false;
4077 }
4078 }
4079 }
4080 if (!klass->IsInterface() && klass->HasSuperClass()) {
4081 mirror::Class* super_class = klass->GetSuperClass();
4082 if (!can_init_parents && !super_class->IsInitialized()) {
4083 return false;
4084 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004085 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004086 return false;
4087 }
4088 }
4089 }
4090 return true;
4091}
4092
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004093bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004094 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004095 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4096
4097 // Are we already initialized and therefore done?
4098 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4099 // an initialized class will never change its state.
4100 if (klass->IsInitialized()) {
4101 return true;
4102 }
4103
4104 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004105 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004106 return false;
4107 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004108
Ian Rogers7b078e82014-09-10 14:44:24 -07004109 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004110 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004111 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004112 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004113
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004114 // Re-check under the lock in case another thread initialized ahead of us.
4115 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004116 return true;
4117 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004118
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004119 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004120 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004121 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004122 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004123 return false;
4124 }
4125
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004126 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004127
4128 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004129 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004130 if (!klass->IsVerified()) {
4131 // We failed to verify, expect either the klass to be erroneous or verification failed at
4132 // compile time.
4133 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004134 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004135 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004136 } else {
4137 CHECK(Runtime::Current()->IsCompiler());
4138 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004139 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004140 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004141 } else {
4142 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004143 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004144 }
4145
Brian Carlstromd1422f82011-09-28 11:37:09 -07004146 // If the class is kStatusInitializing, either this thread is
4147 // initializing higher up the stack or another thread has beat us
4148 // to initializing and we need to wait. Either way, this
4149 // invocation of InitializeClass will not be responsible for
4150 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004151 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004152 // Could have got an exception during verification.
4153 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004154 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004155 return false;
4156 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004157 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004158 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004159 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004160 return true;
4161 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004162 // No. That's fine. Wait for another thread to finish initializing.
4163 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004164 }
4165
4166 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004167 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004168 return false;
4169 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004170 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004171
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004172 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004173
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004174 // From here out other threads may observe that we're initializing and so changes of state
4175 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004176 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004177 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004178
4179 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004180 }
4181
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004182 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004183 if (!klass->IsInterface() && klass->HasSuperClass()) {
4184 mirror::Class* super_class = klass->GetSuperClass();
4185 if (!super_class->IsInitialized()) {
4186 CHECK(!super_class->IsInterface());
4187 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004188 StackHandleScope<1> hs(self);
4189 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004190 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004191 if (!super_initialized) {
4192 // The super class was verified ahead of entering initializing, we should only be here if
4193 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004194 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004195 << "Super class initialization failed for "
4196 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004197 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004198 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004199 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004200 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004201 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004202 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004203 return false;
4204 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004205 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004206 }
4207
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004208 if (klass->NumStaticFields() > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004209 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004210 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004211 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004212 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004213 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004214 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004215 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4216 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004217 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004218 ClassDataItemIterator field_it(dex_file, class_data);
4219 if (value_it.HasNext()) {
4220 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004221 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004222 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004223 StackHandleScope<1> hs(self);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004224 Handle<mirror::ArtField> field(hs.NewHandle(
4225 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004226 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004227 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004228 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004229 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004230 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004231 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004232 }
4233 }
4234 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004235
Ian Rogersd91d6d62013-09-25 20:26:14 -07004236 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004237 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004238 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004239 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004240 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004241 }
4242
Ian Rogers7b078e82014-09-10 14:44:24 -07004243 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004244 uint64_t t1 = NanoTime();
4245
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004246 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004247 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004248 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004249
4250 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004251 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004252 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004253 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004254 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004255 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4256 RuntimeStats* thread_stats = self->GetStats();
4257 ++global_stats->class_init_count;
4258 ++thread_stats->class_init_count;
4259 global_stats->class_init_time_ns += (t1 - t0);
4260 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004261 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004262 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004263 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004264 std::string temp;
4265 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004266 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004267 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004268 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004269 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004270 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004271 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004272 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004273}
4274
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004275bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004276 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004277 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004278 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004279 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004280 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004281 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004282
4283 // When we wake up, repeat the test for init-in-progress. If
4284 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004285 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004286 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004287 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004288 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004289 return false;
4290 }
4291 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004292 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004293 continue;
4294 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004295 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004296 // Compile time initialization failed.
4297 return false;
4298 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004299 if (klass->IsErroneous()) {
4300 // The caller wants an exception, but it was thrown in a
4301 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004302 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004303 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004304 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004305 return false;
4306 }
4307 if (klass->IsInitialized()) {
4308 return true;
4309 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004310 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004311 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004312 }
Ian Rogers07140832014-09-30 15:43:59 -07004313 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004314}
4315
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004316bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004317 if (klass->IsInterface()) {
4318 return true;
4319 }
Ian Rogers151f2212014-05-06 11:27:27 -07004320 // Begin with the methods local to the superclass.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004321 StackHandleScope<2> hs(Thread::Current());
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004322 MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4323 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004324 if (klass->HasSuperClass() &&
4325 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004326 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4327 mh.ChangeMethod(klass->GetVTableEntry(i));
4328 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004329 if (mh.GetMethod() != super_mh.GetMethod() &&
4330 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4331 ThrowLinkageError(klass.Get(),
4332 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004333 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004334 PrettyMethod(mh.GetMethod()).c_str(),
4335 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004336 return false;
4337 }
4338 }
4339 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004340 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004341 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4342 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4343 for (uint32_t j = 0; j < num_methods; ++j) {
4344 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4345 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004346 if (mh.GetMethod() != super_mh.GetMethod() &&
4347 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4348 ThrowLinkageError(klass.Get(),
4349 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004350 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004351 PrettyMethod(mh.GetMethod()).c_str(),
4352 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004353 return false;
4354 }
4355 }
4356 }
4357 }
4358 return true;
4359}
4360
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004361bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4362 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004363 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004364 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004365 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004366 return true;
4367 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004368 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004369 if (!success) {
4370 if (can_init_fields && can_init_parents) {
4371 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4372 }
4373 } else {
4374 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004375 }
4376 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004377}
4378
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004379void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4380 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4381 if (fields != nullptr) {
4382 for (int index = 0; index < fields->GetLength(); index ++) {
4383 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4384 fields->Get(index)->SetDeclaringClass(new_class);
4385 }
4386 }
4387 }
4388
4389 fields = new_class->GetSFields();
4390 if (fields != nullptr) {
4391 for (int index = 0; index < fields->GetLength(); index ++) {
4392 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4393 fields->Get(index)->SetDeclaringClass(new_class);
4394 }
4395 }
4396 }
4397
4398 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4399 if (methods != nullptr) {
4400 for (int index = 0; index < methods->GetLength(); index ++) {
4401 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4402 methods->Get(index)->SetDeclaringClass(new_class);
4403 }
4404 }
4405 }
4406
4407 methods = new_class->GetVirtualMethods();
4408 if (methods != nullptr) {
4409 for (int index = 0; index < methods->GetLength(); index ++) {
4410 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4411 methods->Get(index)->SetDeclaringClass(new_class);
4412 }
4413 }
4414 }
4415}
4416
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004417bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4418 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004419 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004420 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004421
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004422 if (!LinkSuperClass(klass)) {
4423 return false;
4424 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004425 if (!LinkMethods(self, klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004426 return false;
4427 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004428 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004429 return false;
4430 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004431 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004432 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004433 return false;
4434 }
4435 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004436 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004437
4438 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4439 // We don't need to retire this class as it has no embedded tables or it was created the
4440 // correct size during class linker initialization.
4441 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4442
4443 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4444 klass->PopulateEmbeddedImtAndVTable();
4445 }
4446
4447 // This will notify waiters on klass that saw the not yet resolved
4448 // class in the class_table_ during EnsureResolved.
4449 klass->SetStatus(mirror::Class::kStatusResolved, self);
4450 *new_class = klass.Get();
4451 } else {
4452 CHECK(!klass->IsResolved());
4453 // Retire the temporary class and create the correctly sized resolved class.
4454 *new_class = klass->CopyOf(self, class_size);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004455 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004456 CHECK(self->IsExceptionPending()); // Expect an OOME.
4457 klass->SetStatus(mirror::Class::kStatusError, self);
4458 return false;
4459 }
4460
4461 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4462 StackHandleScope<1> hs(self);
4463 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4464 ObjectLock<mirror::Class> lock(self, new_class_h);
4465
4466 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4467
4468 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004469 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004470
4471 // This will notify waiters on temp class that saw the not yet resolved class in the
4472 // class_table_ during EnsureResolved.
4473 klass->SetStatus(mirror::Class::kStatusRetired, self);
4474
4475 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4476 // This will notify waiters on new_class that saw the not yet resolved
4477 // class in the class_table_ during EnsureResolved.
4478 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004479 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004480 return true;
4481}
4482
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004483bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004484 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004485 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4486 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004487 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004488 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004489 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004490 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004491 return false;
4492 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004493 // Verify
4494 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004495 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004496 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004497 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004498 return false;
4499 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004500 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004501 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004502 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004503 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004504 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004505 for (size_t i = 0; i < interfaces->Size(); i++) {
4506 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004507 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004508 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004509 DCHECK(Thread::Current()->IsExceptionPending());
4510 return false;
4511 }
4512 // Verify
4513 if (!klass->CanAccess(interface)) {
4514 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004515 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004516 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004517 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004518 return false;
4519 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004520 }
4521 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004522 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004523 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004524 return true;
4525}
4526
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004527bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004528 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004529 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004530 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004531 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004532 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004533 return false;
4534 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004535 return true;
4536 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004537 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004538 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4539 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004540 return false;
4541 }
4542 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004543 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004544 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004545 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004546 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004547 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004548 return false;
4549 }
4550 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004551 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004552 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004553 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004554 return false;
4555 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004556
Brian Carlstromf3632832014-05-20 15:36:53 -07004557 // Inherit kAccClassIsFinalizable from the superclass in case this
4558 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004559 if (super->IsFinalizable()) {
4560 klass->SetFinalizable();
4561 }
4562
Elliott Hughes2da50362011-10-10 16:57:08 -07004563 // Inherit reference flags (if any) from the superclass.
4564 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4565 if (reference_flags != 0) {
4566 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4567 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004568 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004569 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004570 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004571 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004572 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004573 return false;
4574 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004575
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004576 if (kIsDebugBuild) {
4577 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004578 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004579 CHECK(super->IsResolved());
4580 super = super->GetSuperClass();
4581 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004582 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004583 return true;
4584}
4585
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004586// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004587bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
4588 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004589 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004590 if (klass->IsInterface()) {
4591 // No vtable.
4592 size_t count = klass->NumVirtualMethods();
4593 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004594 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004595 return false;
4596 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004597 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004598 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004599 }
jeffhaobdb76512011-09-07 11:43:16 -07004600 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004601 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004602 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07004603 // Link virtual and interface method tables
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004604 return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004605 }
4606 return true;
4607}
4608
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004609bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004610 if (klass->HasSuperClass()) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004611 uint32_t max_count = klass->NumVirtualMethods() +
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004612 klass->GetSuperClass()->GetVTableLength();
4613 size_t actual_count = klass->GetSuperClass()->GetVTableLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004614 CHECK_LE(actual_count, max_count);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004615 StackHandleScope<4> hs(self);
4616 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004617 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004618 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4619 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4620 if (UNLIKELY(vtable.Get() == nullptr)) {
4621 CHECK(self->IsExceptionPending()); // OOME.
4622 return false;
4623 }
4624 int len = super_class->GetVTableLength();
Mingyao Yang1a128582014-07-22 17:33:25 -07004625 for (int i = 0; i < len; i++) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004626 vtable->Set<false>(i, super_class->GetVTableEntry(i));
4627 }
4628 } else {
Mingyao Yang38eecb02014-08-13 14:51:03 -07004629 CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004630 vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4631 if (UNLIKELY(vtable.Get() == nullptr)) {
4632 CHECK(self->IsExceptionPending()); // OOME.
4633 return false;
4634 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004635 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004636
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004637 // See if any of our virtual methods override the superclass.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004638 MutableMethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4639 MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004640 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004641 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004642 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004643 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004644 for (; j < actual_count; ++j) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004645 mirror::ArtMethod* super_method = vtable->Get(j);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004646 super_mh.ChangeMethod(super_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004647 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004648 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4649 super_method->GetAccessFlags())) {
Elliott Hughes39717372012-07-13 16:21:23 -07004650 if (super_method->IsFinal()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004651 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
Elliott Hughes39717372012-07-13 16:21:23 -07004652 PrettyMethod(local_method).c_str(),
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004653 super_method->GetDeclaringClassDescriptor());
Elliott Hughes39717372012-07-13 16:21:23 -07004654 return false;
4655 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004656 vtable->Set<false>(j, local_method);
Elliott Hughes39717372012-07-13 16:21:23 -07004657 local_method->SetMethodIndex(j);
4658 break;
4659 } else {
4660 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4661 << " would have incorrectly overridden the package-private method in "
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004662 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004663 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004664 }
4665 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07004666 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004667 // Not overriding, append.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004668 vtable->Set<false>(actual_count, local_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004669 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004670 actual_count += 1;
4671 }
4672 }
4673 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004674 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004675 return false;
4676 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004677 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004678 CHECK_LE(actual_count, max_count);
4679 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004680 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004681 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004682 CHECK(self->IsExceptionPending()); // OOME.
4683 return false;
4684 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004685 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004686 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004687 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004688 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004689 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004690 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004691 ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004692 return false;
4693 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004694 StackHandleScope<1> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004695 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004696 vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004697 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004698 CHECK(self->IsExceptionPending()); // OOME.
4699 return false;
4700 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004701 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004702 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004703 vtable->Set<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004704 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004705 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004706 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004707 }
4708 return true;
4709}
4710
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004711bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass,
4712 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004713 Thread* const self = Thread::Current();
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004714 Runtime* const runtime = Runtime::Current();
Jeff Hao88474b42013-10-23 16:24:40 -07004715 // Set the imt table to be all conflicts by default.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004716 klass->SetImTable(runtime->GetDefaultImt());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004717 size_t super_ifcount;
4718 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004719 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004720 } else {
4721 super_ifcount = 0;
4722 }
Mathieu Chartierf8322842014-05-16 10:59:25 -07004723 uint32_t num_interfaces =
4724 interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4725 size_t ifcount = super_ifcount + num_interfaces;
4726 for (size_t i = 0; i < num_interfaces; i++) {
4727 mirror::Class* interface =
4728 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4729 interfaces->Get(i);
4730 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004731 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004732 if (ifcount == 0) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004733 // Class implements no interfaces.
4734 DCHECK_EQ(klass->GetIfTableCount(), 0);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004735 DCHECK(klass->GetIfTable() == nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004736 return true;
4737 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004738 if (ifcount == super_ifcount) {
4739 // Class implements same interfaces as parent, are any of these not marker interfaces?
4740 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004741 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Ian Rogers9bc81912012-10-11 21:43:36 -07004742 for (size_t i = 0; i < ifcount; ++i) {
4743 if (super_iftable->GetMethodArrayCount(i) > 0) {
4744 has_non_marker_interface = true;
4745 break;
4746 }
4747 }
4748 if (!has_non_marker_interface) {
4749 // Class just inherits marker interfaces from parent so recycle parent's iftable.
4750 klass->SetIfTable(super_iftable);
4751 return true;
4752 }
4753 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004754 StackHandleScope<5> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004755 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004756 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004757 CHECK(self->IsExceptionPending()); // OOME.
4758 return false;
4759 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004760 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004761 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004762 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004763 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004764 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004765 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004766 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004767 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004768 // Flatten the interface inheritance hierarchy.
4769 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004770 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004771 mirror::Class* interface =
Mathieu Chartierf8322842014-05-16 10:59:25 -07004772 interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4773 interfaces->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004774 DCHECK(interface != nullptr);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004775 if (!interface->IsInterface()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004776 std::string temp;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004777 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4778 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers1ff3c982014-08-12 02:30:58 -07004779 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004780 return false;
4781 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004782 // Check if interface is already in iftable
4783 bool duplicate = false;
4784 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004785 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004786 if (existing_interface == interface) {
4787 duplicate = true;
4788 break;
4789 }
4790 }
4791 if (!duplicate) {
4792 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004793 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004794 // Add this interface's non-duplicate super-interfaces.
4795 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004796 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004797 bool super_duplicate = false;
4798 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004799 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004800 if (existing_interface == super_interface) {
4801 super_duplicate = true;
4802 break;
4803 }
4804 }
4805 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004806 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004807 }
4808 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004809 }
4810 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004811 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004812 // Shrink iftable in case duplicates were found
4813 if (idx < ifcount) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004814 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004815 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004816 CHECK(self->IsExceptionPending()); // OOME.
4817 return false;
4818 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004819 ifcount = idx;
4820 } else {
4821 CHECK_EQ(idx, ifcount);
4822 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004823 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004824
4825 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004826 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004827 return true;
4828 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004829 self->AllowThreadSuspension();
Jeff Hao88474b42013-10-23 16:24:40 -07004830 // Allocate imtable
4831 bool imtable_changed = false;
Ian Rogers700a4022014-05-19 16:49:03 -07004832 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004833 hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004834 if (UNLIKELY(imtable.Get() == nullptr)) {
Jeff Hao88474b42013-10-23 16:24:40 -07004835 CHECK(self->IsExceptionPending()); // OOME.
4836 return false;
4837 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004838 MutableMethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4839 MutableMethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004840 size_t max_miranda_methods = 0; // The max size of miranda_list.
4841 for (size_t i = 0; i < ifcount; ++i) {
4842 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4843 }
4844 Handle<mirror::ObjectArray<mirror::ArtMethod>>
4845 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
4846 size_t miranda_list_size = 0; // The current size of miranda_list.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004847 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004848 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004849 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004850 if (num_methods > 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004851 StackHandleScope<2> hs(self);
Ian Rogers700a4022014-05-19 16:49:03 -07004852 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004853 method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4854 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004855 CHECK(self->IsExceptionPending()); // OOME.
4856 return false;
4857 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004858 iftable->SetMethodArray(i, method_array.Get());
Ian Rogers700a4022014-05-19 16:49:03 -07004859 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004860 hs.NewHandle(klass->GetVTableDuringLinking()));
Ian Rogers62d6c772013-02-27 08:32:07 -08004861 for (size_t j = 0; j < num_methods; ++j) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004862 interface_mh.ChangeMethod(iftable->GetInterface(i)->GetVirtualMethod(j));
Ian Rogers9bc81912012-10-11 21:43:36 -07004863 int32_t k;
4864 // For each method listed in the interface's method list, find the
4865 // matching method in our class's method list. We want to favor the
4866 // subclass over the superclass, which just requires walking
4867 // back from the end of the vtable. (This only matters if the
4868 // superclass defines a private method and this class redefines
4869 // it -- otherwise it would use the same vtable slot. In .dex files
4870 // those don't end up in the virtual method table, so it shouldn't
4871 // matter which direction we go. We walk it backward anyway.)
4872 for (k = vtable->GetLength() - 1; k >= 0; --k) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004873 vtable_mh.ChangeMethod(vtable->Get(k));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004874 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004875 if (!vtable_mh.Get()->IsAbstract() && !vtable_mh.Get()->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004876 ThrowIllegalAccessError(
4877 klass.Get(),
4878 "Method '%s' implementing interface method '%s' is not public",
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004879 PrettyMethod(vtable_mh.Get()).c_str(),
4880 PrettyMethod(interface_mh.Get()).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004881 return false;
4882 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004883 method_array->Set<false>(j, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004884 // Place method in imt if entry is empty, place conflict otherwise.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004885 uint32_t imt_index = interface_mh.Get()->GetDexMethodIndex() % mirror::Class::kImtSize;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004886 if (imtable->Get(imt_index) == nullptr) {
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004887 imtable->Set<false>(imt_index, vtable_mh.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004888 imtable_changed = true;
4889 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004890 imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -07004891 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004892 break;
4893 }
4894 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004895 if (k < 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004896 StackHandleScope<1> hs(self);
4897 auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004898 for (size_t l = 0; l < miranda_list_size; ++l) {
4899 mirror::ArtMethod* mir_method = miranda_list->Get(l);
4900 DCHECK(mir_method != nullptr);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004901 vtable_mh.ChangeMethod(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004902 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004903 miranda_method.Assign(mir_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004904 break;
4905 }
4906 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004907 if (miranda_method.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004908 // Point the interface table at a phantom slot.
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004909 miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_mh.Get()->Clone(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004910 if (UNLIKELY(miranda_method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004911 CHECK(self->IsExceptionPending()); // OOME.
4912 return false;
4913 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004914 DCHECK_LT(miranda_list_size, max_miranda_methods);
4915 miranda_list->Set<false>(miranda_list_size++, miranda_method.Get());
Ian Rogers9bc81912012-10-11 21:43:36 -07004916 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004917 method_array->Set<false>(j, miranda_method.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004918 }
4919 }
4920 }
4921 }
Jeff Hao88474b42013-10-23 16:24:40 -07004922 if (imtable_changed) {
4923 // Fill in empty entries in interface method table with conflict.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004924 mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004925 for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004926 if (imtable->Get(i) == nullptr) {
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004927 imtable->Set<false>(i, imt_conflict_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004928 }
4929 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004930 klass->SetImTable(imtable.Get());
Jeff Hao88474b42013-10-23 16:24:40 -07004931 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004932 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004933 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004934 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004935 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4936 if (old_method_count == 0) {
4937 virtuals = AllocArtMethodArray(self, new_method_count);
4938 } else {
4939 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4940 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004941 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004942 CHECK(self->IsExceptionPending()); // OOME.
4943 return false;
4944 }
4945 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004946
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004947 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004948 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004949 hs.NewHandle(klass->GetVTableDuringLinking()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004950 CHECK(vtable.Get() != nullptr);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004951 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004952 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004953 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004954 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004955 CHECK(self->IsExceptionPending()); // OOME.
4956 return false;
4957 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004958 for (size_t i = 0; i < miranda_list_size; ++i) {
4959 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004960 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004961 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4962 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4963 klass->SetVirtualMethod(old_method_count + i, method);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004964 vtable->Set<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004965 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004966 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004967 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004968 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004969
Brian Carlstromea46f952013-07-30 01:26:50 -07004970 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
Elliott Hughes4681c802011-09-25 18:04:37 -07004971 for (int i = 0; i < vtable->GetLength(); ++i) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004972 CHECK(vtable->Get(i) != nullptr);
Elliott Hughes4681c802011-09-25 18:04:37 -07004973 }
4974
Ian Rogers7b078e82014-09-10 14:44:24 -07004975 self->AllowThreadSuspension();
Elliott Hughes4681c802011-09-25 18:04:37 -07004976
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004977 return true;
4978}
4979
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004980bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004981 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004982 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004983}
4984
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004985bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004986 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004987 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004988}
4989
Brian Carlstromdbc05252011-09-09 01:59:59 -07004990struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004991 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4992 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004993 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004994 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004995 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004996 // 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 -07004997 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4998 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004999 if (type1 != type2) {
5000 bool is_primitive1 = type1 != Primitive::kPrimNot;
5001 bool is_primitive2 = type2 != Primitive::kPrimNot;
Fred Shih37f05ef2014-07-16 18:38:08 -07005002 if (type1 != type2) {
5003 if (is_primitive1 && is_primitive2) {
5004 // Larger primitive types go first.
5005 return Primitive::ComponentSize(type1) > Primitive::ComponentSize(type2);
5006 } else {
5007 // Reference always goes first.
5008 return !is_primitive1;
5009 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08005010 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005011 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07005012 // same basic group? then sort by string.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005013 return strcmp(field1->GetName(), field2->GetName()) < 0;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005014 }
5015};
5016
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005017bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005018 size_t* class_size) {
5019 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005020 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005021 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005022
Brian Carlstromea46f952013-07-30 01:26:50 -07005023 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005024 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005025
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005026 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005027 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005028 if (is_static) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005029 uint32_t base = sizeof(mirror::Class); // Static fields come after the class.
5030 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
5031 // Static fields come after the embedded tables.
5032 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
Fred Shih37f05ef2014-07-16 18:38:08 -07005033 0, 0, 0, 0, 0);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005034 }
5035 field_offset = MemberOffset(base);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005036 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005037 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005038 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005039 CHECK(super_class->IsResolved())
5040 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005041 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005042 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005043 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005044
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005045 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005046
Brian Carlstromdbc05252011-09-09 01:59:59 -07005047 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005048 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005049 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005050 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005051 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005052 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005053 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005054 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005055 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005056 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005057 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5058 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005059
Fred Shih381e4ca2014-08-25 17:24:27 -07005060 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005061 size_t current_field = 0;
5062 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005063 FieldGaps gaps;
5064
Brian Carlstromdbc05252011-09-09 01:59:59 -07005065 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005066 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005067 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005068 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005069 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005070 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005071 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005072 if (UNLIKELY(!IsAligned<4>(field_offset.Uint32Value()))) {
5073 MemberOffset old_offset = field_offset;
5074 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5075 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5076 }
5077 DCHECK(IsAligned<4>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005078 grouped_and_sorted_fields.pop_front();
5079 num_reference_fields++;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005080 fields->Set<false>(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005081 field->SetOffset(field_offset);
5082 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005083 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005084 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5085 // otherwise we could end up with suboptimal gap fills.
5086 ShuffleForward<8>(num_fields, &current_field, &field_offset,
5087 fields, &grouped_and_sorted_fields, &gaps);
5088 ShuffleForward<4>(num_fields, &current_field, &field_offset,
5089 fields, &grouped_and_sorted_fields, &gaps);
5090 ShuffleForward<2>(num_fields, &current_field, &field_offset,
5091 fields, &grouped_and_sorted_fields, &gaps);
5092 ShuffleForward<1>(num_fields, &current_field, &field_offset,
5093 fields, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005094 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5095 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005096 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005097
Elliott Hughesadb460d2011-10-05 17:02:34 -07005098 // 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 -07005099 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005100 // We know there are no non-reference fields in the Reference classes, and we know
5101 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005102 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005103 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005104 --num_reference_fields;
5105 }
5106
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005107 if (kIsDebugBuild) {
5108 // Make sure that all reference fields appear before
5109 // non-reference fields, and all double-wide fields are aligned.
5110 bool seen_non_ref = false;
5111 for (size_t i = 0; i < num_fields; i++) {
5112 mirror::ArtField* field = fields->Get(i);
5113 if (false) { // enable to debug field layout
5114 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005115 << " class=" << PrettyClass(klass.Get())
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005116 << " field=" << PrettyField(field)
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07005117 << " offset="
5118 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005119 }
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005120 Primitive::Type type = field->GetTypeAsPrimitiveType();
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005121 bool is_primitive = type != Primitive::kPrimNot;
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005122 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005123 strcmp("referent", field->GetName()) == 0) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005124 is_primitive = true; // We lied above, so we have to expect a lie here.
5125 }
5126 if (is_primitive) {
5127 if (!seen_non_ref) {
5128 seen_non_ref = true;
Brian Carlstromf3632832014-05-20 15:36:53 -07005129 DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005130 }
5131 } else {
Brian Carlstromf3632832014-05-20 15:36:53 -07005132 DCHECK(!seen_non_ref) << PrettyField(field);
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005133 }
5134 }
5135 if (!seen_non_ref) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005136 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005137 }
5138 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005139
5140 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005141 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005142 if (is_static) {
5143 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005144 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005145 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005146 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005147 if (!klass->IsVariableSize()) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005148 std::string temp;
5149 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005150 size_t previous_size = klass->GetObjectSize();
5151 if (previous_size != 0) {
5152 // Make sure that we didn't originally have an incorrect size.
Ian Rogers1ff3c982014-08-12 02:30:58 -07005153 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005154 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005155 klass->SetObjectSize(size);
5156 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005157 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005158 return true;
5159}
5160
5161// Set the bitmap of reference offsets, refOffsets, from the ifields
5162// list.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005163void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005164 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005165 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005166 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005167 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005168 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005169 // Compute reference offsets unless our superclass overflowed.
5170 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5171 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
5172 mirror::ObjectArray<mirror::ArtField>* fields = klass->GetIFields();
5173 // All of the fields that contain object references are guaranteed
5174 // to be at the beginning of the fields list.
5175 for (size_t i = 0; i < num_reference_fields; ++i) {
5176 // Note that byte_offset is the offset from the beginning of
5177 // object, not the offset into instance data
5178 mirror::ArtField* field = fields->Get(i);
5179 MemberOffset byte_offset = field->GetOffsetDuringLinking();
5180 uint32_t displaced_bitmap_position =
5181 (byte_offset.Uint32Value() - mirror::kObjectHeaderSize) /
5182 sizeof(mirror::HeapReference<mirror::Object>);
5183 if (displaced_bitmap_position >= 32) {
5184 // Can't encode offset so fall back on slow-path.
5185 reference_offsets = mirror::Class::kClassWalkSuper;
5186 break;
5187 } else {
5188 reference_offsets |= (1 << displaced_bitmap_position);
5189 }
5190 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005191 }
5192 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005193 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005194}
5195
Mathieu Chartier590fee92013-09-13 13:46:47 -07005196mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005197 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005198 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005199 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005200 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005201 return resolved;
5202 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005203 uint32_t utf16_length;
5204 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005205 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005206 dex_cache->SetResolvedString(string_idx, string);
5207 return string;
5208}
5209
Mathieu Chartier590fee92013-09-13 13:46:47 -07005210mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005211 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005212 StackHandleScope<2> hs(Thread::Current());
5213 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5214 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005215 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5216}
5217
5218mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005219 Handle<mirror::DexCache> dex_cache,
5220 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005221 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005222 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005223 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005224 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005225 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005226 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005227 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005228 // TODO: we used to throw here if resolved's class loader was not the
5229 // boot class loader. This was to permit different classes with the
5230 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005231 dex_cache->SetResolvedType(type_idx, resolved);
5232 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005233 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005234 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005235 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005236 StackHandleScope<1> hs(self);
5237 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005238 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005239 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005240 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005241 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005242 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005243 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005244 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005245 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005246 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005247 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005248 return resolved;
5249}
5250
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005251mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005252 Handle<mirror::DexCache> dex_cache,
5253 Handle<mirror::ClassLoader> class_loader,
5254 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005255 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005256 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005257 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005258 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005259 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005260 return resolved;
5261 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005262 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005263 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005264 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005265 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005266 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005267 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005268 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005269 // Scan using method_idx, this saves string compares but will only hit for matching dex
5270 // caches/files.
5271 switch (type) {
5272 case kDirect: // Fall-through.
5273 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005274 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005275 break;
5276 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005277 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005278 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005279 break;
5280 case kSuper: // Fall-through.
5281 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005282 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005283 break;
5284 default:
5285 LOG(FATAL) << "Unreachable - invocation type: " << type;
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005286 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005287 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005288 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005289 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005290 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005291 switch (type) {
5292 case kDirect: // Fall-through.
5293 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005294 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005295 break;
5296 case kInterface:
5297 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005298 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005299 break;
5300 case kSuper: // Fall-through.
5301 case kVirtual:
5302 resolved = klass->FindVirtualMethod(name, signature);
5303 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005304 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005305 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005306 // If we found a method, check for incompatible class changes.
5307 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005308 // Be a good citizen and update the dex cache to speed subsequent calls.
5309 dex_cache->SetResolvedMethod(method_idx, resolved);
5310 return resolved;
5311 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005312 // If we had a method, it's an incompatible-class-change error.
5313 if (resolved != nullptr) {
5314 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5315 } else {
5316 // We failed to find the method which means either an access error, an incompatible class
5317 // change, or no such method. First try to find the method among direct and virtual methods.
5318 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5319 const Signature signature = dex_file.GetMethodSignature(method_id);
5320 switch (type) {
5321 case kDirect:
5322 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005323 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005324 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5325 // have had a resolved method before, which triggers the "true" branch above.
5326 break;
5327 case kInterface:
5328 case kVirtual:
5329 case kSuper:
5330 resolved = klass->FindDirectMethod(name, signature);
5331 break;
5332 }
5333
5334 // If we found something, check that it can be accessed by the referrer.
5335 if (resolved != nullptr && referrer.Get() != nullptr) {
5336 mirror::Class* methods_class = resolved->GetDeclaringClass();
5337 mirror::Class* referring_class = referrer->GetDeclaringClass();
5338 if (!referring_class->CanAccess(methods_class)) {
5339 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5340 resolved, type);
5341 return nullptr;
5342 } else if (!referring_class->CanAccessMember(methods_class,
5343 resolved->GetAccessFlags())) {
5344 ThrowIllegalAccessErrorMethod(referring_class, resolved);
5345 return nullptr;
5346 }
5347 }
5348
5349 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5350 // methods and throw if we find the method there. If we find nothing, throw a
5351 // NoSuchMethodError.
5352 switch (type) {
5353 case kDirect:
5354 case kStatic:
5355 if (resolved != nullptr) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005356 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005357 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005358 resolved = klass->FindInterfaceMethod(name, signature);
5359 if (resolved != nullptr) {
5360 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5361 } else {
5362 ThrowNoSuchMethodError(type, klass, name, signature);
5363 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005364 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005365 break;
5366 case kInterface:
5367 if (resolved != nullptr) {
5368 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Ian Rogers08f753d2012-08-24 14:35:25 -07005369 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005370 resolved = klass->FindVirtualMethod(name, signature);
5371 if (resolved != nullptr) {
5372 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5373 } else {
5374 ThrowNoSuchMethodError(type, klass, name, signature);
5375 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005376 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005377 break;
5378 case kSuper:
Andreas Gampedf733752014-08-25 20:55:01 -07005379 if (resolved != nullptr) {
5380 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5381 } else {
5382 ThrowNoSuchMethodError(type, klass, name, signature);
5383 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005384 break;
5385 case kVirtual:
5386 if (resolved != nullptr) {
5387 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5388 } else {
5389 resolved = klass->FindInterfaceMethod(name, signature);
5390 if (resolved != nullptr) {
5391 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5392 } else {
5393 ThrowNoSuchMethodError(type, klass, name, signature);
5394 }
5395 }
5396 break;
5397 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005398 }
5399 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005400 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005401 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005402}
5403
Mathieu Chartier590fee92013-09-13 13:46:47 -07005404mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005405 Handle<mirror::DexCache> dex_cache,
5406 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005407 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005408 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005409 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005410 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005411 return resolved;
5412 }
5413 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005414 Thread* const self = Thread::Current();
5415 StackHandleScope<1> hs(self);
5416 Handle<mirror::Class> klass(
5417 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005418 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005419 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005420 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005421 }
5422
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005423 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005424 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005425 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005426 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005427 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005428
Andreas Gampe58a5af82014-07-31 16:23:49 -07005429 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005430 const char* name = dex_file.GetFieldName(field_id);
5431 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5432 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005433 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005434 } else {
5435 resolved = klass->FindInstanceField(name, type);
5436 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005437 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005438 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005439 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005440 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005441 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005442 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005443 return resolved;
5444}
5445
Brian Carlstromea46f952013-07-30 01:26:50 -07005446mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005447 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005448 Handle<mirror::DexCache> dex_cache,
5449 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005450 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005451 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005452 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005453 return resolved;
5454 }
5455 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005456 Thread* self = Thread::Current();
5457 StackHandleScope<1> hs(self);
5458 Handle<mirror::Class> klass(
5459 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005460 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005461 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005462 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005463 }
5464
Ian Rogersdfb325e2013-10-30 01:00:44 -07005465 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5466 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005467 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005468 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005469 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005470 dex_cache->SetResolvedField(field_idx, resolved);
5471 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005472 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005473 }
5474 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005475}
5476
Brian Carlstromea46f952013-07-30 01:26:50 -07005477const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005478 uint32_t* length) {
5479 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5480 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005481 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005482 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005483 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005484}
5485
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005486void ClassLinker::DumpAllClasses(int flags) {
5487 if (dex_cache_image_class_lookup_required_) {
5488 MoveImageClassesToClassTable();
5489 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005490 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5491 // 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 -08005492 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005493 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005494 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005495 for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5496 mirror::Class* klass = it.second.Read();
Hiroshi Yamauchia91a4bc2014-06-13 16:44:55 -07005497 all_classes.push_back(klass);
Ian Rogers5d76c432011-10-31 21:42:49 -07005498 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005499 }
5500
5501 for (size_t i = 0; i < all_classes.size(); ++i) {
5502 all_classes[i]->DumpClass(std::cerr, flags);
5503 }
5504}
5505
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005506static OatFile::OatMethod CreateOatMethod(const void* code, const uint8_t* gc_map,
5507 bool is_portable) {
5508 CHECK_EQ(kUsePortableCompiler, is_portable);
5509 CHECK(code != nullptr);
5510 const uint8_t* base;
5511 uint32_t code_offset, gc_map_offset;
5512 if (gc_map == nullptr) {
5513 base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5514 base -= sizeof(void*); // Move backward so that code_offset != 0.
5515 code_offset = sizeof(void*);
5516 gc_map_offset = 0;
5517 } else {
5518 // TODO: 64bit support.
5519 base = nullptr; // Base of data in oat file, ie 0.
5520 code_offset = PointerToLowMemUInt32(code);
5521 gc_map_offset = PointerToLowMemUInt32(gc_map);
5522 }
5523 return OatFile::OatMethod(base, code_offset, gc_map_offset);
5524}
5525
5526bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5527 return (entry_point == GetPortableResolutionStub()) ||
5528 (portable_resolution_trampoline_ == entry_point);
5529}
5530
5531bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5532 return (entry_point == GetQuickResolutionStub()) ||
5533 (quick_resolution_trampoline_ == entry_point);
5534}
5535
5536bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5537 return (entry_point == GetPortableToInterpreterBridge());
5538 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5539}
5540
5541bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5542 return (entry_point == GetQuickToInterpreterBridge()) ||
5543 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5544}
5545
5546bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5547 return (entry_point == GetQuickGenericJniStub()) ||
5548 (quick_generic_jni_trampoline_ == entry_point);
5549}
5550
5551const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5552 return GetQuickGenericJniStub();
5553}
5554
5555void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5556 bool is_portable) const {
5557 OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr, is_portable);
5558 oat_method.LinkMethod(method);
5559 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5560 // Create bridges to transition between different kinds of compiled bridge.
5561 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5562 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5563 } else {
5564 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5565 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5566 method->SetIsPortableCompiled();
5567 }
5568}
5569
5570void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5571 if (!method->IsNative()) {
5572 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5573 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5574 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5575 } else {
5576 const void* quick_method_code = GetQuickGenericJniStub();
5577 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, nullptr, false);
5578 oat_method.LinkMethod(method);
5579 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5580 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5581 }
5582}
5583
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005584void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005585 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005586 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005587 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005588 MoveImageClassesToClassTable();
5589 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005590 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005591 os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005592}
5593
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005594size_t ClassLinker::NumLoadedClasses() {
5595 if (dex_cache_image_class_lookup_required_) {
5596 MoveImageClassesToClassTable();
5597 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005598 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005599 return class_table_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005600}
5601
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005602pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005603 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005604}
5605
5606pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005607 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005608}
5609
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005610void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005611 DCHECK(!init_done_);
5612
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005613 DCHECK(klass != nullptr);
5614 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005615
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005616 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005617 DCHECK(class_roots != nullptr);
5618 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005619 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005620}
5621
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005622const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5623 static const char* class_roots_descriptors[] = {
5624 "Ljava/lang/Class;",
5625 "Ljava/lang/Object;",
5626 "[Ljava/lang/Class;",
5627 "[Ljava/lang/Object;",
5628 "Ljava/lang/String;",
5629 "Ljava/lang/DexCache;",
5630 "Ljava/lang/ref/Reference;",
5631 "Ljava/lang/reflect/ArtField;",
5632 "Ljava/lang/reflect/ArtMethod;",
5633 "Ljava/lang/reflect/Proxy;",
5634 "[Ljava/lang/String;",
5635 "[Ljava/lang/reflect/ArtField;",
5636 "[Ljava/lang/reflect/ArtMethod;",
5637 "Ljava/lang/ClassLoader;",
5638 "Ljava/lang/Throwable;",
5639 "Ljava/lang/ClassNotFoundException;",
5640 "Ljava/lang/StackTraceElement;",
5641 "Z",
5642 "B",
5643 "C",
5644 "D",
5645 "F",
5646 "I",
5647 "J",
5648 "S",
5649 "V",
5650 "[Z",
5651 "[B",
5652 "[C",
5653 "[D",
5654 "[F",
5655 "[I",
5656 "[J",
5657 "[S",
5658 "[Ljava/lang/StackTraceElement;",
5659 };
5660 COMPILE_ASSERT(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5661 mismatch_between_class_descriptors_and_class_root_enum);
5662
5663 const char* descriptor = class_roots_descriptors[class_root];
5664 CHECK(descriptor != nullptr);
5665 return descriptor;
5666}
5667
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005668} // namespace art