blob: 00f28517fd017985a44b48f9181377e4eb77799d [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070020#include <iostream>
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070022#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070024#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070025#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070026
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080028#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010029#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080030#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080031#include "base/unix_file/fd_file.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000033#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080034#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070035#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070036#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070037#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
40#include "gc/heap.h"
41#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070042#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070043#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070044#include "interpreter/interpreter.h"
Ian Rogers0571d352011-11-03 19:51:38 -070045#include "leb128.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
Fred Shih381e4ca2014-08-25 17:24:27 -0700149// Gap between two fields in object layout.
150struct FieldGap {
151 uint32_t start_offset; // The offset from the start of the object.
152 uint32_t size; // The gap size of 1, 2, or 4 bytes.
153};
154struct FieldGapsComparator {
155 explicit FieldGapsComparator() {
156 }
157 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
158 NO_THREAD_SAFETY_ANALYSIS {
159 // Sort by gap size, largest first.
160 return lhs.size > rhs.size;
161 }
162};
163typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
164
165// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800166static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700167 DCHECK(gaps != nullptr);
168
169 uint32_t current_offset = gap_start;
170 while (current_offset != gap_end) {
171 size_t remaining = gap_end - current_offset;
172 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
173 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
174 current_offset += sizeof(uint32_t);
175 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
176 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
177 current_offset += sizeof(uint16_t);
178 } else {
179 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
180 current_offset += sizeof(uint8_t);
181 }
182 DCHECK_LE(current_offset, gap_end) << "Overran gap";
183 }
184}
185// Shuffle fields forward, making use of gaps whenever possible.
186template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000187static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700188 MemberOffset* field_offset,
Fred Shih381e4ca2014-08-25 17:24:27 -0700189 std::deque<mirror::ArtField*>* grouped_and_sorted_fields,
190 FieldGaps* gaps)
191 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
192 DCHECK(current_field_idx != nullptr);
193 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700194 DCHECK(gaps != nullptr);
195 DCHECK(field_offset != nullptr);
196
197 DCHECK(IsPowerOfTwo(n));
198 while (!grouped_and_sorted_fields->empty()) {
199 mirror::ArtField* field = grouped_and_sorted_fields->front();
200 Primitive::Type type = field->GetTypeAsPrimitiveType();
201 if (Primitive::ComponentSize(type) < n) {
202 break;
203 }
204 if (!IsAligned<n>(field_offset->Uint32Value())) {
205 MemberOffset old_offset = *field_offset;
206 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
207 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
208 }
209 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
210 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700211 if (!gaps->empty() && gaps->top().size >= n) {
212 FieldGap gap = gaps->top();
213 gaps->pop();
214 DCHECK(IsAligned<n>(gap.start_offset));
215 field->SetOffset(MemberOffset(gap.start_offset));
216 if (gap.size > n) {
217 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
218 }
219 } else {
220 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
221 field->SetOffset(*field_offset);
222 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
223 }
224 ++(*current_field_idx);
225 }
226}
227
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800228ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700229 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700230 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700231 dex_cache_image_class_lookup_required_(false),
232 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800233 class_roots_(nullptr),
234 array_iftable_(nullptr),
235 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700236 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800237 log_new_dex_caches_roots_(false),
238 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700239 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800240 portable_resolution_trampoline_(nullptr),
241 quick_resolution_trampoline_(nullptr),
242 portable_imt_conflict_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800243 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100244 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800245 quick_to_interpreter_bridge_trampoline_(nullptr),
246 image_pointer_size_(sizeof(void*)) {
Ian Rogers98379392014-02-24 16:53:16 -0800247 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700248}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700249
Alex Light64ad14d2014-08-19 14:23:13 -0700250void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800251 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700252 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700253
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700254 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700255
Elliott Hughes30646832011-10-13 16:59:46 -0700256 // java_lang_Class comes first, it's needed for AllocClass
Ian Rogers1f539342012-10-03 21:09:42 -0700257 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -0700258 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700259 // 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 -0800260 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700261 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
262 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700263 heap->AllocNonMovableObject<true>(self, nullptr,
264 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700265 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700266 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700267 mirror::Class::SetClassClass(java_lang_Class.Get());
268 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700269 if (kUseBakerOrBrooksReadBarrier) {
270 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800271 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700272 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700273 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800274 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800275 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700276
Elliott Hughes418d20f2011-09-22 14:00:39 -0700277 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700278 Handle<mirror::Class> class_array_class(hs.NewHandle(
279 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700280 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700281
Ian Rogers23435d02012-09-24 11:23:12 -0700282 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700283 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
284 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700285 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700286 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700287 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700288 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700289
Ian Rogers23435d02012-09-24 11:23:12 -0700290 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700291 Handle<mirror::Class> object_array_class(hs.NewHandle(
292 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700293 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700294
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700295 // Setup the char (primitive) class to be used for char[].
296 Handle<mirror::Class> char_class(hs.NewHandle(
297 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700298 // The primitive char class won't be initialized by
299 // InitializePrimitiveClass until line 459, but strings (and
300 // internal char arrays) will be allocated before that and the
301 // component size, which is computed from the primitive type, needs
302 // to be set here.
303 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700304
Ian Rogers23435d02012-09-24 11:23:12 -0700305 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700306 Handle<mirror::Class> char_array_class(hs.NewHandle(
307 AllocClass(self, java_lang_Class.Get(),
308 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700309 char_array_class->SetComponentType(char_class.Get());
310 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700311
Ian Rogers23435d02012-09-24 11:23:12 -0700312 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700313 Handle<mirror::Class> java_lang_String(hs.NewHandle(
314 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700315 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700316 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700317 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400318
Fred Shih4ee7a662014-07-11 09:59:27 -0700319 // Setup Reference.
320 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
321 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
322 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
323 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
324 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
325
Ian Rogers23435d02012-09-24 11:23:12 -0700326 // Create storage for root classes, save away our work so far (requires descriptors).
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700327 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
328 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
329 kClassRootsMax));
330 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700331 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
332 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
333 SetClassRoot(kClassArrayClass, class_array_class.Get());
334 SetClassRoot(kObjectArrayClass, object_array_class.Get());
335 SetClassRoot(kCharArrayClass, char_array_class.Get());
336 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700337 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338
339 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700340 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
341 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
342 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
343 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
344 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
345 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
346 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
347 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348
Ian Rogers23435d02012-09-24 11:23:12 -0700349 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700350 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351
Ian Rogers23435d02012-09-24 11:23:12 -0700352 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700353 Handle<mirror::Class> int_array_class(hs.NewHandle(
354 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700356 mirror::IntArray::SetArrayClass(int_array_class.Get());
357 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700359 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700360
Ian Rogers52813c92012-10-11 11:50:38 -0700361 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700362 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
363 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700364 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700365 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700366 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700367
Brian Carlstromf3632832014-05-20 15:36:53 -0700368 // Constructor, Field, Method, and AbstractMethod are necessary so
369 // that FindClass can link members.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700370 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
371 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700372 CHECK(java_lang_reflect_ArtField.Get() != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700373 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700374 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700375 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700376 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700377
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700378 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
379 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700380 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800381 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700382 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700383 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700384 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700385
386 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700387 Handle<mirror::Class> object_array_string(hs.NewHandle(
388 AllocClass(self, java_lang_Class.Get(),
389 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700390 object_array_string->SetComponentType(java_lang_String.Get());
391 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700392
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700393 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
394 AllocClass(self, java_lang_Class.Get(),
395 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700396 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
397 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700398
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700399 Handle<mirror::Class> object_array_art_field(hs.NewHandle(
400 AllocClass(self, java_lang_Class.Get(),
401 mirror::ObjectArray<mirror::ArtField>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700402 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
403 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700404
Ian Rogers23435d02012-09-24 11:23:12 -0700405 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
406 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
407 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700408 CHECK_NE(0U, boot_class_path.size());
Mathieu Chartier2d721012014-11-10 11:08:06 -0800409 for (const DexFile* dex_file : boot_class_path) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700410 CHECK(dex_file != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700411 AppendToBootClassPath(self, *dex_file);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700412 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
414 // now we can use FindSystemClass
415
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700416 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700417 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
418 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700419
Jeff Hao88474b42013-10-23 16:24:40 -0700420 // Create runtime resolution and imt conflict methods. Also setup the default imt.
421 Runtime* runtime = Runtime::Current();
422 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
423 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700424 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700425 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
426
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700427 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
428 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700429 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Alex Light64ad14d2014-08-19 14:23:13 -0700430 if (!runtime->IsCompiler()) {
431 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700432 quick_resolution_trampoline_ = GetQuickResolutionStub();
433 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
434 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700435 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700436
Mathieu Chartier66f19252012-09-18 08:57:04 -0700437 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700438 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800439 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700440 CHECK_EQ(java_lang_Object.Get(), Object_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700441 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700442 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800443 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700444 std::ostringstream os1, os2;
445 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
446 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
447 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
448 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700449 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800450 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700451 CHECK_EQ(java_lang_String.Get(), String_class);
452 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700453 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454
Ian Rogers23435d02012-09-24 11:23:12 -0700455 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800456 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800457 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458
Ian Rogers98379392014-02-24 16:53:16 -0800459 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800460 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700461
Ian Rogers98379392014-02-24 16:53:16 -0800462 mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700463 CHECK_EQ(char_array_class.Get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464
Ian Rogers98379392014-02-24 16:53:16 -0800465 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800466 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467
Ian Rogers98379392014-02-24 16:53:16 -0800468 mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700469 CHECK_EQ(int_array_class.Get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470
Ian Rogers98379392014-02-24 16:53:16 -0800471 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800472 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700473
Ian Rogers98379392014-02-24 16:53:16 -0800474 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800475 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700476
Ian Rogers98379392014-02-24 16:53:16 -0800477 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800478 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700479
Ian Rogers98379392014-02-24 16:53:16 -0800480 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700481 CHECK_EQ(class_array_class.Get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700482
Ian Rogers98379392014-02-24 16:53:16 -0800483 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700484 CHECK_EQ(object_array_class.Get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700485
Ian Rogers23435d02012-09-24 11:23:12 -0700486 // Setup the single, global copy of "iftable".
Ian Rogers98379392014-02-24 16:53:16 -0800487 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700488 CHECK(java_lang_Cloneable != nullptr);
Ian Rogers98379392014-02-24 16:53:16 -0800489 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700490 CHECK(java_io_Serializable != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700491 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
492 // crawl up and explicitly list all of the supers as well.
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700493 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700494 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700495 array_iftable->SetInterface(0, java_lang_Cloneable);
496 array_iftable->SetInterface(1, java_io_Serializable);
497 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700498
Ian Rogers23435d02012-09-24 11:23:12 -0700499 // Sanity check Class[] and Object[]'s interfaces.
Mathieu Chartierf8322842014-05-16 10:59:25 -0700500 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
501 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
502 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
503 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700504 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700505 // dex_cache_ fields and register them in class_table_.
Ian Rogers98379392014-02-24 16:53:16 -0800506 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700507 CHECK_EQ(java_lang_Class.Get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700508
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700509 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800510 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700511 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700512
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700513 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800514 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700515 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700516
Brian Carlstromf3632832014-05-20 15:36:53 -0700517 mirror::Class* String_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700518 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700519 CHECK_EQ(object_array_string.Get(), String_array_class);
Mathieu Chartier66f19252012-09-18 08:57:04 -0700520
Brian Carlstromea46f952013-07-30 01:26:50 -0700521 mirror::Class* Art_method_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700522 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700523 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700524
Brian Carlstromea46f952013-07-30 01:26:50 -0700525 mirror::Class* Art_field_array_class =
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700526 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700527 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
Ian Rogers4445a7e2012-10-05 17:19:13 -0700528
Ian Rogers23435d02012-09-24 11:23:12 -0700529 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700530
Ian Rogers23435d02012-09-24 11:23:12 -0700531 // Create java.lang.reflect.Proxy root.
Ian Rogers98379392014-02-24 16:53:16 -0800532 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
Ian Rogers466bb252011-10-14 03:29:56 -0700533 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
534
Brian Carlstrom1f870082011-08-23 16:02:11 -0700535 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700536 // finish initializing Reference class
537 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
538 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
539 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
540 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
541 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Brian Carlstromf3632832014-05-20 15:36:53 -0700542 mirror::Class* java_lang_ref_FinalizerReference =
543 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700544 java_lang_ref_FinalizerReference->SetAccessFlags(
545 java_lang_ref_FinalizerReference->GetAccessFlags() |
546 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700547 mirror::Class* java_lang_ref_PhantomReference =
548 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700549 java_lang_ref_PhantomReference->SetAccessFlags(
550 java_lang_ref_PhantomReference->GetAccessFlags() |
551 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700552 mirror::Class* java_lang_ref_SoftReference =
553 FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554 java_lang_ref_SoftReference->SetAccessFlags(
555 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstromf3632832014-05-20 15:36:53 -0700556 mirror::Class* java_lang_ref_WeakReference =
557 FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700558 java_lang_ref_WeakReference->SetAccessFlags(
559 java_lang_ref_WeakReference->GetAccessFlags() |
560 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700561
Ian Rogers23435d02012-09-24 11:23:12 -0700562 // Setup the ClassLoader, verifying the object_size_.
Ian Rogers98379392014-02-24 16:53:16 -0800563 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700564 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700565 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
566
jeffhao8cd6dda2012-02-22 10:15:34 -0800567 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700568 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800569 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800570 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700571 SetClassRoot(kJavaLangClassNotFoundException,
572 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800573 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700574 SetClassRoot(kJavaLangStackTraceElementArrayClass,
575 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800576 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700577
Andreas Gampe76bd8802014-12-10 16:43:58 -0800578 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
579 // initialized.
580 {
581 const DexFile& dex_file = java_lang_Object->GetDexFile();
582 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
583 CHECK(void_string_id != nullptr);
584 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
585 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
586 CHECK(void_type_id != nullptr);
587 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
588 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
589 // as referrer so the used dex cache is core's one.
590 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
591 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
592 self->AssertNoPendingException();
593 }
594
Ian Rogers98379392014-02-24 16:53:16 -0800595 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700596
Brian Carlstroma004aa92012-02-08 18:05:09 -0800597 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700598}
599
Ian Rogers98379392014-02-24 16:53:16 -0800600void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800601 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700602
603 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700604 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700605 // as the types of the field can't be resolved prior to the runtime being
606 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800607 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700608 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800609 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800610
Brian Carlstromea46f952013-07-30 01:26:50 -0700611 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700612 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
613 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700614
Brian Carlstromea46f952013-07-30 01:26:50 -0700615 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700616 CHECK_STREQ(queue->GetName(), "queue");
617 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700618
Brian Carlstromea46f952013-07-30 01:26:50 -0700619 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700620 CHECK_STREQ(queueNext->GetName(), "queueNext");
621 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700622
Brian Carlstromea46f952013-07-30 01:26:50 -0700623 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700624 CHECK_STREQ(referent->GetName(), "referent");
625 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700626
Brian Carlstromea46f952013-07-30 01:26:50 -0700627 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700628 CHECK_STREQ(zombie->GetName(), "zombie");
629 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700630
Brian Carlstroma663ea52011-08-19 23:33:41 -0700631 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700632 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700633 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800634 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700635 CHECK(klass != nullptr);
636 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700637 // note SetClassRoot does additional validation.
638 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700639 }
640
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700641 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700642
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700643 // disable the slow paths in FindClass and CreatePrimitiveClass now
644 // that Object, Class, and Object[] are setup
645 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700646
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800647 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700648}
649
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700650void ClassLinker::RunRootClinits() {
651 Thread* self = Thread::Current();
652 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800653 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700654 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700655 StackHandleScope<1> hs(self);
656 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700657 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700658 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700659 }
660 }
661}
662
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700663bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800664 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000665 const char* oat_cache_filename,
666 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700667 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700668 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800669
Ian Rogers1d54e732013-05-02 21:10:01 -0700670 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800671 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700672 if (heap->GetImageSpace() == nullptr) {
673 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
674 // out of space anyway it might not matter.
675 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
676 "without an image.", dex_filename);
677 return false;
678 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700679 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800680
Brian Carlstrom6449c622014-02-10 23:48:36 -0800681 std::string dex_file_option("--dex-file=");
682 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800683
Brian Carlstrom6449c622014-02-10 23:48:36 -0800684 std::string oat_fd_option("--oat-fd=");
685 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800686
Brian Carlstrom6449c622014-02-10 23:48:36 -0800687 std::string oat_location_option("--oat-location=");
688 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800689
Brian Carlstrom6449c622014-02-10 23:48:36 -0800690 std::vector<std::string> argv;
691 argv.push_back(dex2oat);
692 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800693 argv.push_back("-classpath");
694 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800695 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800696
Ian Rogers8afeb852014-04-02 14:55:49 -0700697 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800698
Jeff Hao4a200f52014-04-01 14:58:49 -0700699 if (!Runtime::Current()->IsVerificationEnabled()) {
700 argv.push_back("--compiler-filter=verify-none");
701 }
702
Alex Light6e183f22014-07-18 14:57:04 -0700703 if (Runtime::Current()->MustRelocateIfPossible()) {
704 argv.push_back("--runtime-arg");
705 argv.push_back("-Xrelocate");
706 } else {
707 argv.push_back("--runtime-arg");
708 argv.push_back("-Xnorelocate");
709 }
710
Brian Carlstrom6449c622014-02-10 23:48:36 -0800711 if (!kIsTargetBuild) {
712 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700713 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700714
Brian Carlstrom6449c622014-02-10 23:48:36 -0800715 argv.push_back(boot_image_option);
716 argv.push_back(dex_file_option);
717 argv.push_back(oat_fd_option);
718 argv.push_back(oat_location_option);
719 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800720 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800721 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700722 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800723
724 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700725}
726
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700727const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700728 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800729 if (kIsDebugBuild) {
730 for (size_t i = 0; i < oat_files_.size(); ++i) {
731 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700732 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800733 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700734 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
735 oat_files_.push_back(oat_file);
736 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800737}
738
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700739OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
740 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700741 OatFile* oat_file = space->ReleaseOatFile();
742 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700743 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700744 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700745}
746
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100747const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800748 const char* dex_location = dex_file.GetLocation().c_str();
749 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100750 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800751}
752
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100753const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
754 const char* dex_location,
755 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700756 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100757 for (const OatFile* oat_file : oat_files_) {
758 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700759
760 if (oat_location != nullptr) {
761 if (oat_file->GetLocation() != oat_location) {
762 continue;
763 }
764 }
765
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700766 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800767 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700768 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100769 if (oat_dex_file != nullptr) {
770 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800771 }
772 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100773 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800774}
775
Calin Juravle621962a2014-09-02 15:53:55 +0100776
777// Loads all multi dex files from the given oat file returning true on success.
778//
779// Parameters:
780// oat_file - the oat file to load from
781// dex_location - the dex location used to generate the oat file
782// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
783// generated - whether or not the oat_file existed before or was just (re)generated
784// error_msgs - any error messages will be appended here
785// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
786static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
787 const char* dex_location,
788 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700789 bool generated,
790 std::vector<std::string>* error_msgs,
791 std::vector<const DexFile*>* dex_files) {
792 if (oat_file == nullptr) {
793 return false;
794 }
795
796 size_t old_size = dex_files->size(); // To rollback on error.
797
798 bool success = true;
799 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100800 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700801 const char* next_name = next_name_str.c_str();
802
Calin Juravle621962a2014-09-02 15:53:55 +0100803 uint32_t next_location_checksum;
804 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700805 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100806 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
807 // When i=0 the multidex name should be the same as the location name. We already have the
808 // checksum it so we don't need to recompute it.
809 if (dex_location_checksum == nullptr) {
810 next_location_checksum_pointer = nullptr;
811 } else {
812 next_location_checksum = *dex_location_checksum;
813 }
814 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700815 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100816 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700817 }
818
819 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
820
821 if (oat_dex_file == nullptr) {
822 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700823 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100824 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700825 oat_file->GetLocation().c_str());
826 error_msgs->push_back(error_msg);
827 }
828 break; // Not found, done.
829 }
830
831 // Checksum test. Test must succeed when generated.
832 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100833 if (next_location_checksum_pointer != nullptr) {
834 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700835 }
836
837 if (success) {
838 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
839 if (dex_file == nullptr) {
840 success = false;
841 error_msgs->push_back(error_msg);
842 } else {
843 dex_files->push_back(dex_file);
844 }
845 }
846
847 // When we generated the file, we expect success, or something is terribly wrong.
848 CHECK_EQ(false, generated && !success)
849 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100850 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700851 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
852 }
853
854 if (dex_files->size() == old_size) {
855 success = false; // We did not even find classes.dex
856 }
857
858 if (success) {
859 return true;
860 } else {
861 // Free all the dex files we have loaded.
862 auto it = dex_files->begin() + old_size;
863 auto it_end = dex_files->end();
864 for (; it != it_end; it++) {
865 delete *it;
866 }
867 dex_files->erase(dex_files->begin() + old_size, it_end);
868
869 return false;
870 }
871}
872
873// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
874// complicates the loading process, as we should not use an iterative loading process, because that
875// would register the oat file and dex files that come before the broken one. Instead, check all
876// multidex ahead of time.
877bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
878 std::vector<std::string>* error_msgs,
879 std::vector<const DexFile*>* dex_files) {
880 // 1) Check whether we have an open oat file.
881 // This requires a dex checksum, use the "primary" one.
882 uint32_t dex_location_checksum;
883 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
884 bool have_checksum = true;
885 std::string checksum_error_msg;
886 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100887 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700888 dex_location_checksum_pointer = nullptr;
889 have_checksum = false;
890 }
891
892 bool needs_registering = false;
893
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100894 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
895 dex_location_checksum_pointer);
896 std::unique_ptr<const OatFile> open_oat_file(
897 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700898
899 // 2) If we do not have an open one, maybe there's one on disk already.
900
901 // In case the oat file is not open, we play a locking game here so
902 // that if two different processes race to load and register or generate
903 // (or worse, one tries to open a partial generated file) we will be okay.
904 // This is actually common with apps that use DexClassLoader to work
905 // around the dex method reference limit and that have a background
906 // service running in a separate process.
907 ScopedFlock scoped_flock;
908
909 if (open_oat_file.get() == nullptr) {
910 if (oat_location != nullptr) {
911 // Can only do this if we have a checksum, else error.
912 if (!have_checksum) {
913 error_msgs->push_back(checksum_error_msg);
914 return false;
915 }
916
917 std::string error_msg;
918
919 // We are loading or creating one in the future. Time to set up the file lock.
920 if (!scoped_flock.Init(oat_location, &error_msg)) {
921 error_msgs->push_back(error_msg);
922 return false;
923 }
924
Alex Lighta59dd802014-07-02 16:28:08 -0700925 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700926 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
927 oat_location, &error_msg));
928
929 if (open_oat_file.get() == nullptr) {
930 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
931 dex_location, oat_location, error_msg.c_str());
932 VLOG(class_linker) << compound_msg;
933 error_msgs->push_back(compound_msg);
934 }
935 } else {
936 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100937 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700938 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
939 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100940 kRuntimeISA, error_msgs,
941 &obsolete_file_cleanup_failed));
942 // There's no point in going forward and eventually try to regenerate the
943 // file if we couldn't remove the obsolete one. Mostly likely we will fail
944 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100945 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
946 if (obsolete_file_cleanup_failed) {
947 return false;
948 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700949 }
950 needs_registering = true;
951 }
952
953 // 3) If we have an oat file, check all contained multidex files for our dex_location.
954 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100955 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
956 dex_location_checksum_pointer,
957 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700958 if (success) {
959 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
960 if (needs_registering) {
961 // We opened the oat file, so we must register it.
962 RegisterOatFile(oat_file);
963 }
Alex Light9dcc4572014-08-14 14:16:26 -0700964 // If the file isn't executable we failed patchoat but did manage to get the dex files.
965 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700966 } else {
967 if (needs_registering) {
968 // We opened it, delete it.
969 open_oat_file.reset();
970 } else {
971 open_oat_file.release(); // Do not delete open oat files.
972 }
973 }
974
975 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
976
977 // Need a checksum, fail else.
978 if (!have_checksum) {
979 error_msgs->push_back(checksum_error_msg);
980 return false;
981 }
982
983 // Look in cache location if no oat_location is given.
984 std::string cache_location;
985 if (oat_location == nullptr) {
986 // Use the dalvik cache.
987 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
988 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
989 oat_location = cache_location.c_str();
990 }
991
Alex Light64ad14d2014-08-19 14:23:13 -0700992 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700993 // Definitely need to lock now.
994 if (!scoped_flock.HasFile()) {
995 std::string error_msg;
996 if (!scoped_flock.Init(oat_location, &error_msg)) {
997 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700998 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700999 }
1000 }
1001
Alex Light64ad14d2014-08-19 14:23:13 -07001002 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001003 // Create the oat file.
1004 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
1005 oat_location, error_msgs));
1006 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001007
1008 // Failed, bail.
1009 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001010 std::string error_msg;
1011 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
1012 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
1013 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -07001014 return false;
1015 }
1016
1017 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001018 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1019 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001020 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001021 if (success) {
1022 RegisterOatFile(open_oat_file.release());
1023 return true;
1024 } else {
1025 return false;
1026 }
1027}
1028
1029const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1030 uint32_t dex_location_checksum,
1031 const char* oat_location,
1032 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001033 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001034 !Runtime::Current()->IsCompiler(),
1035 error_msg));
1036 if (oat_file.get() == nullptr) {
1037 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1038 error_msg->c_str());
1039 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001040 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001041 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001042 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1043 if (image_space != nullptr) {
1044 const ImageHeader& image_header = image_space->GetImageHeader();
1045 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1046 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1047 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1048 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1049 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1050 actual_image_oat_checksum);
1051 return nullptr;
1052 }
1053
1054 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1055 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1056 if (expected_image_oat_offset != actual_image_oat_offset) {
1057 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1058 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1059 actual_image_oat_offset);
1060 return nullptr;
1061 }
1062 int32_t expected_patch_delta = image_header.GetPatchDelta();
1063 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1064 if (expected_patch_delta != actual_patch_delta) {
1065 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1066 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1067 return nullptr;
1068 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001069 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001070
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001071 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1072 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001073 if (oat_dex_file == nullptr) {
1074 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1075 dex_location);
1076 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001077 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001078 uint32_t expected_dex_checksum = dex_location_checksum;
1079 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1080 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001081 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1082 "found 0x%x", oat_location, expected_dex_checksum,
1083 actual_dex_checksum);
1084 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001085 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001086 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1087 if (dex_file.get() != nullptr) {
1088 return oat_file.release();
1089 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001090 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001091 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001092}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001093
Andreas Gampe833a4852014-05-21 18:46:59 -07001094const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1095 int fd, const char* oat_location,
1096 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001097 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001098 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001099 std::string error_msg;
1100 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001101 CHECK(!error_msg.empty());
1102 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001103 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001104 }
Igor Murashkin46774762014-10-22 11:37:02 -07001105 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001106 !Runtime::Current()->IsCompiler(),
1107 &error_msg));
1108 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001109 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1110 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001111 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001112 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001113 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001114
1115 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001116}
1117
Alex Light6e183f22014-07-18 14:57:04 -07001118bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1119 const InstructionSet instruction_set) {
1120 Runtime* runtime = Runtime::Current();
1121 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001122 if (image_space == nullptr) {
1123 return false;
1124 }
Alex Light6e183f22014-07-18 14:57:04 -07001125 uint32_t image_oat_checksum = 0;
1126 if (instruction_set == kRuntimeISA) {
1127 const ImageHeader& image_header = image_space->GetImageHeader();
1128 image_oat_checksum = image_header.GetOatChecksum();
1129 } else {
1130 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1131 image_space->GetImageLocation().c_str(), instruction_set));
1132 image_oat_checksum = image_header->GetOatChecksum();
1133 }
1134 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1135}
1136
1137bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1138 const InstructionSet instruction_set,
1139 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001140 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001141 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001142 if (image_space == nullptr) {
1143 *error_msg = "No image space for verification against";
1144 return false;
1145 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001146
1147 // If the requested instruction set is the same as the current runtime,
1148 // we can use the checksums directly. If it isn't, we'll have to read the
1149 // image header from the image for the right instruction set.
1150 uint32_t image_oat_checksum = 0;
1151 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001152 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001153 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001154 const ImageHeader& image_header = image_space->GetImageHeader();
1155 image_oat_checksum = image_header.GetOatChecksum();
1156 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001157 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001158 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001159 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001160 image_space->GetImageLocation().c_str(), instruction_set));
1161 image_oat_checksum = image_header->GetOatChecksum();
1162 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001163 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001164 }
1165 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001166 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1167
1168 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1169 if (!oat_file->IsPic()) {
1170 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1171 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1172 }
Alex Light6e183f22014-07-18 14:57:04 -07001173 if (!ret) {
1174 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1175 oat_file->GetLocation().c_str(),
1176 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1177 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1178 oat_file->GetOatHeader().GetImagePatchDelta(),
1179 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1180 }
1181 return ret;
1182}
1183
1184bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1185 const char* dex_location,
1186 uint32_t dex_location_checksum,
1187 const InstructionSet instruction_set,
1188 std::string* error_msg) {
1189 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1190 return false;
1191 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001192
Brian Carlstromf3632832014-05-20 15:36:53 -07001193 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1194 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001195 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001196 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1197 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001198 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001199 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001200 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001201 oat_dex_file_in->GetDexFileLocation().c_str(),
1202 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001203 }
1204 return false;
1205 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001206
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001207 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001208 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001209}
1210
Alex Lighta59dd802014-07-02 16:28:08 -07001211bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1212 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001213 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001214 std::string* error_msg) {
1215 CHECK(oat_file != nullptr);
1216 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001217 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001218 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001219 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1220 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1221 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001222 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001223 if (oat_dex_file == nullptr) {
1224 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001225 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001226 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001227 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001228 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001229 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001230 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001231 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001232 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001233 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001234 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001235 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001236 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001237 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001238 }
Alex Lighta59dd802014-07-02 16:28:08 -07001239 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001240}
1241
Andreas Gampe833a4852014-05-21 18:46:59 -07001242const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001243 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001244 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001245 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001246 std::vector<std::string>* error_msgs,
1247 bool* obsolete_file_cleanup_failed) {
1248 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001249 bool already_opened = false;
1250 std::string dex_location_str(dex_location);
1251 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1252 &already_opened,
1253 obsolete_file_cleanup_failed,
1254 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001255 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001256 if (oat_file.get() == nullptr) {
1257 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1258 dex_location));
1259 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001260 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001261 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1262 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001263 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1264 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001265 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001266 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001267 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001268 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001269 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1270 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1271 "dex location '%s'. Image checksum incorrect.",
1272 oat_file->GetLocation().c_str(), dex_location));
1273 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001274 } else {
1275 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001276 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001277}
1278
Brian Carlstromae826982011-11-09 01:33:42 -08001279const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001280 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001281 for (size_t i = 0; i < oat_files_.size(); i++) {
1282 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001283 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001284 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001285 return oat_file;
1286 }
1287 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001288 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001289}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001290
Alex Lighta59dd802014-07-02 16:28:08 -07001291const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1292 InstructionSet isa,
1293 bool *already_opened,
1294 bool *obsolete_file_cleanup_failed,
1295 std::vector<std::string>* error_msgs) {
1296 // Find out if we've already opened the file
1297 const OatFile* ret = nullptr;
1298 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1299 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1300 if (ret != nullptr) {
1301 *already_opened = true;
1302 return ret;
1303 }
1304
1305 std::string dalvik_cache;
1306 bool have_android_data = false;
1307 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001308 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001309 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001310 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001311 std::string cache_filename;
1312 if (have_dalvik_cache) {
1313 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1314 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1315 if (ret != nullptr) {
1316 *already_opened = true;
1317 return ret;
1318 }
1319 } else {
1320 // If we need to relocate we should just place odex back where it started.
1321 cache_filename = odex_filename;
1322 }
1323
1324 ret = nullptr;
1325
1326 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1327 //
1328 // Now we do the following:
1329 // 1) Try and open the odex version
1330 // 2) If present, checksum-verified & relocated correctly return it
1331 // 3) Close the odex version to free up its address space.
1332 // 4) Try and open the cache version
1333 // 5) If present, checksum-verified & relocated correctly return it
1334 // 6) Close the cache version to free up its address space.
1335 // 7) If we should relocate:
1336 // a) If we have opened and checksum-verified the odex version relocate it to
1337 // 'cache_filename' and return it
1338 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1339 // it. This should not happen often (I think only the run-test's will hit this case).
1340 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1341 // this point.
1342 // 9) Return nullptr
1343
1344 *already_opened = false;
1345 const Runtime* runtime = Runtime::Current();
1346 CHECK(runtime != nullptr);
1347 bool executable = !runtime->IsCompiler();
1348
1349 std::string odex_error_msg;
1350 bool should_patch_system = false;
1351 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001352 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001353 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001354 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001355 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001356 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001357 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001358 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001359 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001360 &odex_checksum_verified,
1361 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001362 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001363 } else {
1364 if (odex_checksum_verified) {
1365 // We can just relocate
1366 should_patch_system = true;
1367 odex_error_msg = "Image Patches are incorrect";
1368 }
1369 if (odex_oat_file.get() != nullptr) {
1370 have_system_odex = true;
1371 }
Alex Lighta59dd802014-07-02 16:28:08 -07001372 }
1373 }
1374
Alex Lighta59dd802014-07-02 16:28:08 -07001375 std::string cache_error_msg;
1376 bool should_patch_cache = false;
1377 bool cache_checksum_verified = false;
1378 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001379 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001380 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001381 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001382 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001383 &cache_checksum_verified,
1384 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001385 return cache_oat_file.release();
1386 } else if (cache_checksum_verified) {
1387 // We can just relocate
1388 should_patch_cache = true;
1389 cache_error_msg = "Image Patches are incorrect";
1390 }
1391 } else if (have_android_data) {
1392 // dalvik_cache does not exist but android data does. This means we should be able to create
1393 // it, so we should try.
1394 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1395 }
1396
1397 ret = nullptr;
1398 std::string error_msg;
1399 if (runtime->CanRelocate()) {
1400 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001401 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1402 if (space != nullptr) {
1403 const std::string& image_location = space->GetImageLocation();
1404 if (odex_checksum_verified && should_patch_system) {
1405 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1406 } else if (cache_checksum_verified && should_patch_cache) {
1407 CHECK(have_dalvik_cache);
1408 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1409 }
Alex Light84d76052014-08-22 17:49:35 -07001410 } else if (have_system_odex) {
1411 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001412 }
1413 }
1414 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1415 // implicitly: were able to fine where the cached version is but we were unable to use it,
1416 // either as a destination for relocation or to open a file. We should delete it if it is
1417 // there.
1418 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1419 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1420 "searching for dex file %s: %s",
1421 cache_filename.c_str(), dex_location.c_str(),
1422 strerror(errno));
1423 error_msgs->push_back(rm_error_msg);
1424 VLOG(class_linker) << rm_error_msg;
1425 // Let the caller know that we couldn't remove the obsolete file.
1426 // This is a good indication that further writes may fail as well.
1427 *obsolete_file_cleanup_failed = true;
1428 }
1429 }
1430 if (ret == nullptr) {
1431 VLOG(class_linker) << error_msg;
1432 error_msgs->push_back(error_msg);
1433 std::string relocation_msg;
1434 if (runtime->CanRelocate()) {
1435 relocation_msg = StringPrintf(" and relocation failed");
1436 }
1437 if (have_dalvik_cache && cache_checksum_verified) {
1438 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1439 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1440 cache_filename.c_str(), cache_error_msg.c_str(),
1441 relocation_msg.c_str());
1442 } else {
1443 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1444 "dalvik_cache availible)%s.", odex_filename.c_str(),
1445 odex_error_msg.c_str(), relocation_msg.c_str());
1446 }
1447 VLOG(class_linker) << error_msg;
1448 error_msgs->push_back(error_msg);
1449 }
1450 return ret;
1451}
1452
Alex Light9dcc4572014-08-14 14:16:26 -07001453const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1454 InstructionSet isa,
1455 std::string* error_msg) {
1456 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001457 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001458 if (output.get() == nullptr) {
1459 return nullptr;
1460 }
Alex Light84d76052014-08-22 17:49:35 -07001461 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1462 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001463 return output.release();
1464 } else {
1465 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1466 oat_path.c_str());
1467 return nullptr;
1468 }
1469}
1470
Alex Lighta59dd802014-07-02 16:28:08 -07001471const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1472 const std::string& output_oat,
1473 const std::string& image_location,
1474 InstructionSet isa,
1475 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001476 Runtime* runtime = Runtime::Current();
1477 DCHECK(runtime != nullptr);
1478 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001479 // We don't have an image space so there is no point in trying to patchoat.
1480 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1481 << "running without an image. Attempting to use oat file for interpretation.";
1482 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1483 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001484 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001485 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1486 // input_oat but make sure we only do interpretation on it's dex files.
1487 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1488 << "disabled. Attempting to use oat file for interpretation";
1489 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1490 }
Alex Lighta59dd802014-07-02 16:28:08 -07001491 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001492 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001493
1494 std::string isa_arg("--instruction-set=");
1495 isa_arg += GetInstructionSetString(isa);
1496 std::string input_oat_filename_arg("--input-oat-file=");
1497 input_oat_filename_arg += input_oat;
1498 std::string output_oat_filename_arg("--output-oat-file=");
1499 output_oat_filename_arg += output_oat;
1500 std::string patched_image_arg("--patched-image-location=");
1501 patched_image_arg += image_location;
1502
1503 std::vector<std::string> argv;
1504 argv.push_back(patchoat);
1505 argv.push_back(isa_arg);
1506 argv.push_back(input_oat_filename_arg);
1507 argv.push_back(output_oat_filename_arg);
1508 argv.push_back(patched_image_arg);
1509
1510 std::string command_line(Join(argv, ' '));
1511 LOG(INFO) << "Relocate Oat File: " << command_line;
1512 bool success = Exec(argv, error_msg);
1513 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001514 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001515 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001516 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001517 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1518 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001519 return output.release();
1520 } else if (output.get() != nullptr) {
1521 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1522 "but output file '%s' failed verifcation: %s",
1523 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1524 } else {
1525 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1526 "but was unable to open output file '%s': %s",
1527 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1528 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001529 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001530 // patchoat failed which means we probably don't have enough room to place the output oat file,
1531 // instead of failing we should just run the interpreter from the dex files in the input oat.
1532 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1533 << "for interpretation. patchoat failure was: " << *error_msg;
1534 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001535 } else {
1536 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1537 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1538 error_msg->c_str());
1539 }
1540 return nullptr;
1541}
1542
Andreas Gampe7ba64962014-10-23 11:37:40 -07001543bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001544 bool* checksum_verified,
1545 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001546 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001547 if (image_space == nullptr) {
1548 *error_msg = "No image space present";
1549 return false;
1550 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001551 uint32_t real_image_checksum;
1552 void* real_image_oat_offset;
1553 int32_t real_patch_delta;
1554 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001555 const ImageHeader& image_header = image_space->GetImageHeader();
1556 real_image_checksum = image_header.GetOatChecksum();
1557 real_image_oat_offset = image_header.GetOatDataBegin();
1558 real_patch_delta = image_header.GetPatchDelta();
1559 } else {
1560 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1561 image_space->GetImageLocation().c_str(), isa));
1562 real_image_checksum = image_header->GetOatChecksum();
1563 real_image_oat_offset = image_header->GetOatDataBegin();
1564 real_patch_delta = image_header->GetPatchDelta();
1565 }
1566
1567 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001568 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001569
1570 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1571 *checksum_verified = oat_image_checksum == real_image_checksum;
1572 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001573 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1574 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001575 }
1576
Andreas Gampe7ba64962014-10-23 11:37:40 -07001577 bool offset_verified;
1578 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001579
Andreas Gampe7ba64962014-10-23 11:37:40 -07001580 if (!oat_file->IsPic()) {
1581 // If an oat file is not PIC, we need to check that the image is at the expected location and
1582 // patched in the same way.
1583 void* oat_image_oat_offset =
1584 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1585 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1586 if (!offset_verified) {
1587 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1588 real_image_oat_offset, oat_image_oat_offset);
1589 }
1590
1591 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1592 patch_delta_verified = oat_patch_delta == real_patch_delta;
1593 if (!patch_delta_verified) {
1594 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1595 "received 0x%x)", real_patch_delta, oat_patch_delta);
1596 }
1597 } else {
1598 // If an oat file is PIC, we ignore offset and patching delta.
1599 offset_verified = true;
1600 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001601 }
1602
1603 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001604 if (!ret) {
1605 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001606 }
1607 return ret;
1608}
1609
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001610const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1611 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001612 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001613 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001614 return oat_file;
1615 }
1616
Igor Murashkin46774762014-10-22 11:37:02 -07001617 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001618 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001619}
1620
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001621void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001622 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001623 DCHECK(obj != nullptr);
1624 DCHECK(class_linker != nullptr);
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001625 size_t pointer_size = class_linker->image_pointer_size_;
Ian Rogers848871b2013-08-05 10:56:33 -07001626
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001627 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001628 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001629 if (!method->IsNative()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001630 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001631 if (method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001632 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1633 pointer_size);
1634 method->SetEntryPointFromPortableCompiledCodePtrSize(GetPortableToInterpreterBridge(),
1635 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001636 }
1637 }
1638 }
1639}
1640
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001641void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001642 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001643 CHECK(!init_done_);
1644
Mathieu Chartier590fee92013-09-13 13:46:47 -07001645 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001646 gc::Heap* heap = Runtime::Current()->GetHeap();
1647 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001648 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001649 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001650 OatFile& oat_file = GetImageOatFile(space);
1651 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1652 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001653 const char* image_file_location = oat_file.GetOatHeader().
1654 GetStoreValueByKey(OatHeader::kImageLocationKey);
1655 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001656 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1657 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001658 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1659 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001660 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001661 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001662 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1663 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1664 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001665
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001666 StackHandleScope<1> hs(self);
1667 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1668 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1669 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001670 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001671
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001672 // Special case of setting up the String class early so that we can test arbitrary objects
1673 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001674 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001675
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001676 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001677 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001678 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001679 StackHandleScope<1> hs2(self);
1680 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001681 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001682 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1683 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001684 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001685 std::string error_msg;
1686 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001687 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001688 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001689 << " from within oat file " << oat_file.GetLocation()
1690 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001691 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001692 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001693
1694 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1695
1696 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001697 }
1698
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001699 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1700 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001701 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001702 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
1703 if (!Runtime::Current()->IsCompiler()) {
1704 // Compiler supports having an image with a different pointer size than the runtime. This
1705 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1706 // also use 32 bit dex2oat on a system with 64 bit apps.
1707 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1708 << sizeof(void*);
1709 }
1710 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1711 image_pointer_size_ = 4;
1712 } else {
1713 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1714 image_pointer_size_ = 8;
1715 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001716
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001717 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -08001718 Runtime* runtime = Runtime::Current();
1719 if (!runtime->IsCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001720 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001721 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001722 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001723
1724 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001725 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001726 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001727
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001728 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001729 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001730 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001731 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001732 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001733 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001734 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1735 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1736 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1737 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1738 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1739 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1740 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1741 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1742 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1743 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001744
Ian Rogers98379392014-02-24 16:53:16 -08001745 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001746
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001747 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001748}
1749
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001750void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1751 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1752 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001753 for (GcRoot<mirror::Class>& root : class_table_) {
1754 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1755 }
1756 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1757 root.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001758 }
1759 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001760 for (auto& root : new_class_roots_) {
1761 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
1762 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1763 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001764 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001765 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1766 // corresponding object. This is slow, but luckily for us, this may only happen with a
1767 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001768 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
1769 class_table_.Erase(it);
1770 class_table_.Insert(GcRoot<mirror::Class>(new_ref));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001771 }
1772 }
1773 }
1774 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1775 new_class_roots_.clear();
1776 }
1777 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1778 log_new_class_table_roots_ = true;
1779 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1780 log_new_class_table_roots_ = false;
1781 }
1782 // We deliberately ignore the class roots in the image since we
1783 // handle image roots by using the MS/CMS rescanning of dirty cards.
1784}
1785
Brian Carlstroma663ea52011-08-19 23:33:41 -07001786// Keep in sync with InitCallback. Anything we visit, we need to
1787// reinit references to when reinitializing a ClassLinker from a
1788// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001789void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001790 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001791 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001792 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001793 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001794 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001795 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1796 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001797 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001798 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1799 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001800 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001801 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001802 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001803 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1804 new_dex_cache_roots_.clear();
1805 }
1806 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1807 log_new_dex_caches_roots_ = true;
1808 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1809 log_new_dex_caches_roots_ = false;
1810 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001811 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001812 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001813 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1814 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001815 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001816 if (!find_array_class_cache_[i].IsNull()) {
1817 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001818 }
1819 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001820}
1821
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001822void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1823 if (dex_cache_image_class_lookup_required_) {
1824 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001825 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001826 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001827 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001828 for (GcRoot<mirror::Class>& root : class_table_) {
1829 if (!visitor(root.Read(), arg)) {
1830 return;
1831 }
1832 }
1833 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1834 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001835 return;
1836 }
1837 }
1838}
1839
Ian Rogersdbf3be02014-08-29 15:40:08 -07001840static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001841 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001842 classes->insert(c);
1843 return true;
1844}
1845
Ian Rogersdbf3be02014-08-29 15:40:08 -07001846struct GetClassesVisitorArrayArg {
1847 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1848 int32_t index;
1849 bool success;
1850};
1851
1852static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1853 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1854 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1855 if (arg->index < (*arg->classes)->GetLength()) {
1856 (*arg->classes)->Set(arg->index, c);
1857 arg->index++;
1858 return true;
1859 } else {
1860 arg->success = false;
1861 return false;
1862 }
1863}
1864
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001865void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001866 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1867 // is avoiding duplicates.
1868 if (!kMovingClasses) {
1869 std::set<mirror::Class*> classes;
1870 VisitClasses(GetClassesVisitorSet, &classes);
1871 for (mirror::Class* klass : classes) {
1872 if (!visitor(klass, arg)) {
1873 return;
1874 }
1875 }
1876 } else {
1877 Thread* self = Thread::Current();
1878 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001879 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001880 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1881 GetClassesVisitorArrayArg local_arg;
1882 local_arg.classes = &classes;
1883 local_arg.success = false;
1884 // We size the array assuming classes won't be added to the class table during the visit.
1885 // If this assumption fails we iterate again.
1886 while (!local_arg.success) {
1887 size_t class_table_size;
1888 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001889 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001890 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001891 }
1892 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1893 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1894 classes.Assign(
1895 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1896 CHECK(classes.Get() != nullptr); // OOME.
1897 local_arg.index = 0;
1898 local_arg.success = true;
1899 VisitClasses(GetClassesVisitorArray, &local_arg);
1900 }
1901 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1902 // If the class table shrank during creation of the clases array we expect null elements. If
1903 // the class table grew then the loop repeats. If classes are created after the loop has
1904 // finished then we don't visit.
1905 mirror::Class* klass = classes->Get(i);
1906 if (klass != nullptr && !visitor(klass, arg)) {
1907 return;
1908 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001909 }
1910 }
1911}
1912
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001913ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001914 mirror::Class::ResetClass();
1915 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001916 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001917 mirror::ArtField::ResetClass();
1918 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001919 mirror::BooleanArray::ResetArrayClass();
1920 mirror::ByteArray::ResetArrayClass();
1921 mirror::CharArray::ResetArrayClass();
1922 mirror::DoubleArray::ResetArrayClass();
1923 mirror::FloatArray::ResetArrayClass();
1924 mirror::IntArray::ResetArrayClass();
1925 mirror::LongArray::ResetArrayClass();
1926 mirror::ShortArray::ResetArrayClass();
1927 mirror::Throwable::ResetClass();
1928 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001929 STLDeleteElements(&boot_class_path_);
1930 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001931}
1932
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001933mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001934 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001935 StackHandleScope<16> hs(self);
1936 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1937 Handle<mirror::DexCache> dex_cache(
1938 hs.NewHandle(down_cast<mirror::DexCache*>(
1939 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1940 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001941 if (dex_cache.Get() == nullptr) {
1942 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001943 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001944 Handle<mirror::String>
1945 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001946 if (location.Get() == nullptr) {
1947 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001948 }
Ian Rogers700a4022014-05-19 16:49:03 -07001949 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001950 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001951 if (strings.Get() == nullptr) {
1952 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001953 }
Ian Rogers700a4022014-05-19 16:49:03 -07001954 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001955 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001956 if (types.Get() == nullptr) {
1957 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001958 }
Ian Rogers700a4022014-05-19 16:49:03 -07001959 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001960 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001961 if (methods.Get() == nullptr) {
1962 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001963 }
Ian Rogers700a4022014-05-19 16:49:03 -07001964 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001965 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001966 if (fields.Get() == nullptr) {
1967 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001968 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001969 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1970 fields.Get());
1971 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001972}
1973
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001974mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001975 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001976 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001977 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001978 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001979 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001980 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1981 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001982 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001983 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001984 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001985 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001986 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001987}
1988
Ian Rogers6fac4472014-02-25 17:01:10 -08001989mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001990 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001991}
1992
Brian Carlstromea46f952013-07-30 01:26:50 -07001993mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001994 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001995 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001996}
1997
Brian Carlstromea46f952013-07-30 01:26:50 -07001998mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001999 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08002000 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002001}
2002
Mathieu Chartier590fee92013-09-13 13:46:47 -07002003mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2004 Thread* self, size_t length) {
2005 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2006 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002007}
2008
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002009mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
2010 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002011 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002012
2013 // For temporary classes we must wait for them to be retired.
2014 if (init_done_ && klass->IsTemp()) {
2015 CHECK(!klass->IsResolved());
2016 if (klass->IsErroneous()) {
2017 ThrowEarlierClassFailure(klass);
2018 return nullptr;
2019 }
2020 StackHandleScope<1> hs(self);
2021 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2022 ObjectLock<mirror::Class> lock(self, h_class);
2023 // Loop and wait for the resolving thread to retire this class.
2024 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2025 lock.WaitIgnoringInterrupts();
2026 }
2027 if (h_class->IsErroneous()) {
2028 ThrowEarlierClassFailure(h_class.Get());
2029 return nullptr;
2030 }
2031 CHECK(h_class->IsRetired());
2032 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002033 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2034 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002035 }
2036
Brian Carlstromaded5f72011-10-07 17:15:04 -07002037 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002038 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002039 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002040 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2041 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002042 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002043 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2044 ThrowClassCircularityError(h_class.Get());
2045 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002046 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002047 }
2048 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002049 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002050 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002051 }
2052 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002053
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002054 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002055 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002056 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002057 }
2058 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002059 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002060 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002061 return klass;
2062}
2063
Ian Rogers68b56852014-08-29 20:19:11 -07002064typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2065
2066// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002067ClassPathEntry FindInClassPath(const char* descriptor,
2068 size_t hash, const std::vector<const DexFile*>& class_path) {
2069 for (const DexFile* dex_file : class_path) {
2070 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002071 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002072 return ClassPathEntry(dex_file, dex_class_def);
2073 }
2074 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002075 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002076}
2077
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002078mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2079 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002080 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002081 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002082 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002083 if (class_loader->GetClass() !=
2084 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2085 class_loader->GetParent()->GetClass() !=
2086 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2087 return nullptr;
2088 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002089 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002090 // Check if this would be found in the parent boot class loader.
2091 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002092 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002093 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002094 // May return null if resolution on another thread fails.
2095 klass = EnsureResolved(self, descriptor, klass);
2096 } else {
2097 // May OOME.
2098 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2099 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002100 }
Ian Rogers32427292014-11-19 14:05:21 -08002101 if (klass == nullptr) {
2102 CHECK(self->IsExceptionPending()) << descriptor;
2103 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002104 }
Ian Rogers32427292014-11-19 14:05:21 -08002105 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002106 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002107 // Handle as if this is the child PathClassLoader.
2108 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002109 StackHandleScope<3> hs(self);
2110 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2111 // We need to get the DexPathList and loop through it.
2112 Handle<mirror::ArtField> cookie_field =
2113 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2114 Handle<mirror::ArtField> dex_file_field =
2115 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002116 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002117 mirror::Object* dex_path_list =
2118 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2119 GetObject(class_loader.Get());
2120 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2121 cookie_field.Get() != nullptr) {
2122 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2123 mirror::Object* dex_elements_obj =
2124 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2125 GetObject(dex_path_list);
2126 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2127 // at the mCookie which is a DexFile vector.
2128 if (dex_elements_obj != nullptr) {
2129 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2130 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2131 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2132 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2133 if (element == nullptr) {
2134 // Should never happen, fall back to java code to throw a NPE.
2135 break;
2136 }
2137 mirror::Object* dex_file = dex_file_field->GetObject(element);
2138 if (dex_file != nullptr) {
2139 const uint64_t cookie = cookie_field->GetLong(dex_file);
2140 auto* dex_files =
2141 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2142 if (dex_files == nullptr) {
2143 // This should never happen so log a warning.
2144 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2145 break;
2146 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002147 for (const DexFile* cp_dex_file : *dex_files) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002148 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002149 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002150 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002151 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2152 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002153 if (klass == nullptr) {
2154 CHECK(self->IsExceptionPending()) << descriptor;
2155 self->ClearException();
2156 return nullptr;
2157 }
2158 return klass;
2159 }
2160 }
2161 }
2162 }
2163 }
2164 }
Ian Rogers32427292014-11-19 14:05:21 -08002165 self->AssertNoPendingException();
2166 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002167 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002168}
2169
Ian Rogers98379392014-02-24 16:53:16 -08002170mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002171 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002172 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002173 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002174 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002175 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002176 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2177 // for primitive classes that aren't backed by dex files.
2178 return FindPrimitiveClass(descriptor[0]);
2179 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002180 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002181 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002182 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002183 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002184 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002185 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002186 // Class is not yet loaded.
2187 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002188 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002189 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002190 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002191 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002192 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002193 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002194 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002195 } else {
2196 // The boot class loader is searched ahead of the application class loader, failures are
2197 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2198 // trigger the chaining with a proper stack trace.
2199 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2200 self->SetException(ThrowLocation(), pre_allocated);
2201 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002202 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002203 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002204 // First try with the bootstrap class loader.
2205 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002206 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002207 if (klass != nullptr) {
2208 return EnsureResolved(self, descriptor, klass);
2209 }
2210 }
Ian Rogers63557452014-06-04 16:57:15 -07002211 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2212 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002213 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002214 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002215 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002216 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002217 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002218 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002219 const std::vector<const DexFile*>* class_path;
2220 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002221 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002222 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002223 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002224 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2225 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002226 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002227 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002228 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002229 } else {
2230 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2231 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2232 self->SetException(ThrowLocation(), pre_allocated);
2233 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002234 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002235 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002236 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002237 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2238 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002239 if (cp_klass != nullptr) {
2240 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002241 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002242 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002243 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002244 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002245 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002246 {
2247 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002248 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2249 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002250 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002251 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002252 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002253 }
Ian Rogers68b56852014-08-29 20:19:11 -07002254 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002255 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2256 WellKnownClasses::java_lang_ClassLoader_loadClass,
2257 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002258 }
Ian Rogers98379392014-02-24 16:53:16 -08002259 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002260 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002261 return nullptr;
2262 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002263 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002264 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002265 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002266 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002267 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002268 // success, return mirror::Class*
2269 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002270 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002271 }
Ian Rogers07140832014-09-30 15:43:59 -07002272 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002273}
2274
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002275mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002276 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002277 const DexFile& dex_file,
2278 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002279 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002280 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002281
Brian Carlstromaded5f72011-10-07 17:15:04 -07002282 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002283 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002284 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002285 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002286 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002287 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002288 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002289 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002291 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2292 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002293 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002294 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002295 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002296 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002297 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002298 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002299 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002300 }
2301
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002302 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002303 // Allocate a class with the status of not ready.
2304 // Interface object should get the right size here. Regular class will
2305 // figure out the right size later and be replaced with one of the right
2306 // size when the class becomes resolved.
2307 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002308 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002309 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002310 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002311 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002312 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002313 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002314 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002315 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002316 if (self->IsExceptionPending()) {
2317 // An exception occured during load, set status to erroneous while holding klass' lock in case
2318 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002319 if (!klass->IsErroneous()) {
2320 klass->SetStatus(mirror::Class::kStatusError, self);
2321 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002322 return nullptr;
2323 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002324 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002325
Mathieu Chartier590fee92013-09-13 13:46:47 -07002326 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002327 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002328 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002329 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2330 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002331 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002332 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002333
Brian Carlstromaded5f72011-10-07 17:15:04 -07002334 // Finish loading (if necessary) by finding parents
2335 CHECK(!klass->IsLoaded());
2336 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2337 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002338 if (!klass->IsErroneous()) {
2339 klass->SetStatus(mirror::Class::kStatusError, self);
2340 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002341 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002342 }
2343 CHECK(klass->IsLoaded());
2344 // Link the class (if necessary)
2345 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002346 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002347 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002348
2349 mirror::Class* new_class = nullptr;
2350 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002351 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002352 if (!klass->IsErroneous()) {
2353 klass->SetStatus(mirror::Class::kStatusError, self);
2354 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002355 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002356 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002357 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002358 CHECK(new_class != nullptr) << descriptor;
2359 CHECK(new_class->IsResolved()) << descriptor;
2360
2361 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002362
2363 /*
2364 * We send CLASS_PREPARE events to the debugger from here. The
2365 * definition of "preparation" is creating the static fields for a
2366 * class and initializing them to the standard default values, but not
2367 * executing any code (that comes later, during "initialization").
2368 *
2369 * We did the static preparation in LinkClass.
2370 *
2371 * The class has been prepared and resolved but possibly not yet verified
2372 * at this point.
2373 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002374 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002375
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002376 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002377}
2378
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002379uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2380 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002381 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002382 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002383 size_t num_8 = 0;
2384 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002385 size_t num_32 = 0;
2386 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002387 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002388 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2389 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002390 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002391 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002392 switch (c) {
2393 case 'L':
2394 case '[':
2395 num_ref++;
2396 break;
2397 case 'J':
2398 case 'D':
2399 num_64++;
2400 break;
2401 case 'I':
2402 case 'F':
2403 num_32++;
2404 break;
2405 case 'S':
2406 case 'C':
2407 num_16++;
2408 break;
2409 case 'B':
2410 case 'Z':
2411 num_8++;
2412 break;
2413 default:
2414 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002415 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002416 }
2417 }
2418 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002419 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002420}
2421
Ian Rogers97b52f82014-08-14 11:34:07 -07002422OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2423 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002424 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002425 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2426 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002427 *found = false;
2428 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002429 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002430 *found = true;
2431 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002432}
2433
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002434static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2435 uint32_t method_idx) {
2436 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002437 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002438 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002439 ClassDataItemIterator it(dex_file, class_data);
2440 // Skip fields
2441 while (it.HasNextStaticField()) {
2442 it.Next();
2443 }
2444 while (it.HasNextInstanceField()) {
2445 it.Next();
2446 }
2447 // Process methods
2448 size_t class_def_method_index = 0;
2449 while (it.HasNextDirectMethod()) {
2450 if (it.GetMemberIndex() == method_idx) {
2451 return class_def_method_index;
2452 }
2453 class_def_method_index++;
2454 it.Next();
2455 }
2456 while (it.HasNextVirtualMethod()) {
2457 if (it.GetMemberIndex() == method_idx) {
2458 return class_def_method_index;
2459 }
2460 class_def_method_index++;
2461 it.Next();
2462 }
2463 DCHECK(!it.HasNext());
2464 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002465 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002466}
2467
Ian Rogers97b52f82014-08-14 11:34:07 -07002468const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002469 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002470 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002471 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002472 size_t oat_method_index;
2473 if (method->IsStatic() || method->IsDirect()) {
2474 // Simple case where the oat method index was stashed at load time.
2475 oat_method_index = method->GetMethodIndex();
2476 } else {
2477 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2478 // by search for its position in the declared virtual methods.
2479 oat_method_index = declaring_class->NumDirectMethods();
2480 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002481 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002482 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002483 // Check method index instead of identity in case of duplicate method definitions.
2484 if (method->GetDexMethodIndex() ==
2485 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002486 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002487 break;
2488 }
Ian Rogersf320b632012-03-13 18:47:47 -07002489 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002490 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002491 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2492 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002493 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002494 DCHECK_EQ(oat_method_index,
2495 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002496 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002497 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002498 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2499 declaring_class->GetDexClassDefIndex(),
2500 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002501 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002502 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002503 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002504 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002505}
2506
2507// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002508const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002509 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002510 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002511 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002512 }
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;
Ian Rogers97b52f82014-08-14 11:34:07 -07002516 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002517 result = oat_method.GetQuickCode();
2518 }
2519
Ian Rogersef7d42f2014-01-06 12:55:46 -08002520 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002521 if (method->IsNative()) {
2522 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002523 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002524 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002525 // No code? Do we expect portable code?
2526 result = GetQuickToPortableBridge();
2527 } else {
2528 // No code? You must mean to go into the interpreter.
2529 result = GetQuickToInterpreterBridge();
2530 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002531 }
2532 return result;
TDYa12785321912012-04-01 15:24:56 -07002533}
2534
Ian Rogersef7d42f2014-01-06 12:55:46 -08002535const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2536 bool* have_portable_code) {
2537 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2538 *have_portable_code = false;
2539 if (method->IsProxyMethod()) {
2540 return GetPortableProxyInvokeHandler();
2541 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002542 bool found;
2543 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002544 const void* result = nullptr;
2545 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002546 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002547 result = oat_method.GetPortableCode();
2548 quick_code = oat_method.GetQuickCode();
2549 }
2550
Ian Rogersef7d42f2014-01-06 12:55:46 -08002551 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002552 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002553 // No code? You must mean to go into the interpreter.
2554 result = GetPortableToInterpreterBridge();
2555 } else {
2556 // No code? But there's quick code, so use a bridge.
2557 result = GetPortableToQuickBridge();
2558 }
2559 } else {
2560 *have_portable_code = true;
2561 }
2562 return result;
2563}
2564
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002565const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2566 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2567 return nullptr;
2568 }
2569 bool found;
2570 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2571 return found ? oat_method.GetQuickCode() : nullptr;
2572}
2573
2574const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2575 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2576 return nullptr;
2577 }
2578 bool found;
2579 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2580 return found ? oat_method.GetPortableCode() : nullptr;
2581}
2582
Ian Rogersef7d42f2014-01-06 12:55:46 -08002583const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2584 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002585 bool found;
2586 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2587 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002588 return nullptr;
2589 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002590 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002591 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002592}
2593
2594const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2595 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002596 bool found;
2597 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2598 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002599 return nullptr;
2600 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002601 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002602 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002603}
2604
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002605// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002606static bool NeedsInterpreter(
2607 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2608 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002609 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002610 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002611 // May return true for native code, in the case of generic JNI
2612 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002613 return true;
2614 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002615#ifdef ART_SEA_IR_MODE
2616 ScopedObjectAccess soa(Thread::Current());
2617 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2618 LOG(INFO) << "Found " << PrettyMethod(method);
2619 return false;
2620 }
2621#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002622 // If interpreter mode is enabled, every method (except native and proxy) must
2623 // be run with interpreter.
2624 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2625 !method->IsNative() && !method->IsProxyMethod();
2626}
2627
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002628void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002629 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002630 if (klass->NumDirectMethods() == 0) {
2631 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002632 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002633 Runtime* runtime = Runtime::Current();
2634 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002635 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2636 return; // OAT file unavailable.
2637 }
Ian Rogers19846512012-02-24 11:42:47 -08002638 }
Alex Light64ad14d2014-08-19 14:23:13 -07002639
Mathieu Chartierf8322842014-05-16 10:59:25 -07002640 const DexFile& dex_file = klass->GetDexFile();
2641 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002642 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002643 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002644 // There should always be class data if there were direct methods.
2645 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002646 ClassDataItemIterator it(dex_file, class_data);
2647 // Skip fields
2648 while (it.HasNextStaticField()) {
2649 it.Next();
2650 }
2651 while (it.HasNextInstanceField()) {
2652 it.Next();
2653 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002654 bool has_oat_class;
2655 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2656 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002657 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002658 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002659 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002660 if (!method->IsStatic()) {
2661 // Only update static methods.
2662 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002663 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002664 const void* portable_code = nullptr;
2665 const void* quick_code = nullptr;
2666 if (has_oat_class) {
2667 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2668 portable_code = oat_method.GetPortableCode();
2669 quick_code = oat_method.GetQuickCode();
2670 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002671 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2672 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002673 if (enter_interpreter) {
2674 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002675 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002676 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002677 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002678 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002679 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002680 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002681 quick_code = GetQuickToInterpreterBridge();
2682 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002683 } else {
2684 if (portable_code == nullptr) {
2685 portable_code = GetPortableToQuickBridge();
2686 } else {
2687 have_portable_code = true;
2688 }
2689 if (quick_code == nullptr) {
2690 quick_code = GetQuickToPortableBridge();
2691 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002692 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002693 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2694 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002695 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002696 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002697}
2698
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002699void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002700 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002701 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002702 Runtime* runtime = Runtime::Current();
2703 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002704 // The following code only applies to a non-compiler runtime.
2705 return;
2706 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002707 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002708 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2709 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002710 if (oat_class != nullptr) {
2711 // Every kind of method should at least get an invoke stub from the oat_method.
2712 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002713 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002714 oat_method.LinkMethod(method.Get());
2715 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002716
Jeff Hao16743632013-05-08 10:59:04 -07002717 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002718 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002719 method->GetEntryPointFromQuickCompiledCode(),
2720 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002721 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002722 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002723 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002724 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002725 }
2726
Brian Carlstrom92827a52011-10-10 15:50:01 -07002727 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002728 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2729 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002730 return;
2731 }
Ian Rogers19846512012-02-24 11:42:47 -08002732
Ian Rogersef7d42f2014-01-06 12:55:46 -08002733 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002734 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002735 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002736 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2737 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002738 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2739 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002740 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002741 if (!method->IsNative()) {
2742 // Set entry point from compiled code if there's no code or in interpreter only mode.
2743 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2744 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2745 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002746 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002747 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2748 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002749 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2750 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2751 have_portable_code = true;
2752 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2753 } else {
2754 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2755 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002756 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002757
Ian Rogers62d6c772013-02-27 08:32:07 -08002758 if (method->IsNative()) {
2759 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002760 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002761
2762 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002763 // We have a native method here without code. Then it should have either the generic JNI
2764 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2765 // TODO: this doesn't handle all the cases where trampolines may be installed.
2766 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2767 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002768 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002769 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002770
Ian Rogers62d6c772013-02-27 08:32:07 -08002771 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002772 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002773 method->GetEntryPointFromQuickCompiledCode(),
2774 method->GetEntryPointFromPortableCompiledCode(),
2775 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002776}
2777
Fred Shih37f05ef2014-07-16 18:38:08 -07002778
Fred Shih37f05ef2014-07-16 18:38:08 -07002779
Ian Rogers7b078e82014-09-10 14:44:24 -07002780void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002781 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002782 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002783 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002784 CHECK(klass.Get() != nullptr);
2785 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002786 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002787 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002788 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002789
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002790 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002791 if (kUseBakerOrBrooksReadBarrier) {
2792 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002793 }
Andreas Gampe51829322014-08-25 15:05:04 -07002794 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002795 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002796 klass->SetAccessFlags(access_flags);
2797 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002798 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002799 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002800
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002801 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002802 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002803 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002804
Ian Rogers13735952014-10-08 12:43:28 -07002805 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002806 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002807 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002808 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002809
Ian Rogers97b52f82014-08-14 11:34:07 -07002810
2811 bool has_oat_class = false;
2812 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2813 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2814 &has_oat_class);
2815 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002816 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002817 }
2818 }
2819 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002820 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002821 }
2822}
2823
Ian Rogers7b078e82014-09-10 14:44:24 -07002824void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002825 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002826 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002827 const OatFile::OatClass* oat_class) {
2828 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002829 ClassDataItemIterator it(dex_file, class_data);
2830 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002831 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002832 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002833 CHECK(self->IsExceptionPending()); // OOME.
2834 return;
2835 }
2836 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002837 }
2838 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002839 mirror::ObjectArray<mirror::ArtField>* fields =
2840 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002841 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002842 CHECK(self->IsExceptionPending()); // OOME.
2843 return;
2844 }
2845 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002846 }
2847 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002848 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002849 StackHandleScope<1> hs(self);
2850 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002851 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002852 CHECK(self->IsExceptionPending()); // OOME.
2853 return;
2854 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002855 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002856 LoadField(dex_file, it, klass, sfield);
2857 }
2858 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002859 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002860 StackHandleScope<1> hs(self);
2861 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002862 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002863 CHECK(self->IsExceptionPending()); // OOME.
2864 return;
2865 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002866 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002867 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002868 }
2869
Ian Rogers0571d352011-11-03 19:51:38 -07002870 // Load methods.
2871 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002872 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002873 mirror::ObjectArray<mirror::ArtMethod>* directs =
2874 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002875 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002876 CHECK(self->IsExceptionPending()); // OOME.
2877 return;
2878 }
2879 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002880 }
Ian Rogers0571d352011-11-03 19:51:38 -07002881 if (it.NumVirtualMethods() != 0) {
2882 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002883 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2884 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002885 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002886 CHECK(self->IsExceptionPending()); // OOME.
2887 return;
2888 }
2889 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002890 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002891 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002892 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2893 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002894 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002895 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002896 StackHandleScope<1> hs(self);
2897 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002898 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002899 CHECK(self->IsExceptionPending()); // OOME.
2900 return;
2901 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002902 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002903 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002904 uint32_t it_method_index = it.GetMemberIndex();
2905 if (last_dex_method_index == it_method_index) {
2906 // duplicate case
2907 method->SetMethodIndex(last_class_def_method_index);
2908 } else {
2909 method->SetMethodIndex(class_def_method_index);
2910 last_dex_method_index = it_method_index;
2911 last_class_def_method_index = class_def_method_index;
2912 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002913 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002914 }
2915 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002916 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002917 StackHandleScope<1> hs(self);
2918 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002919 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002920 CHECK(self->IsExceptionPending()); // OOME.
2921 return;
2922 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002923 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002924 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002925 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002926 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002927 }
2928 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002929}
2930
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002931void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002932 Handle<mirror::Class> klass,
2933 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002934 uint32_t field_idx = it.GetMemberIndex();
2935 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002936 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002937 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002938}
2939
Brian Carlstromea46f952013-07-30 01:26:50 -07002940mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002941 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002942 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002943 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002944 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002945 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002946
Brian Carlstromea46f952013-07-30 01:26:50 -07002947 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002948 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002949 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002950 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002951 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002952 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002953
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002954 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002955 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002956 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002957 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002958
Ian Rogers19846512012-02-24 11:42:47 -08002959 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002960 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002961
Andreas Gampe51829322014-08-25 15:05:04 -07002962 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002963
Ian Rogersdfb325e2013-10-30 01:00:44 -07002964 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002965 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002966 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2967 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002968 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002969 klass->SetFinalizable();
2970 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002971 std::string temp;
2972 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002973 // The Enum class declares a "final" finalize() method to prevent subclasses from
2974 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2975 // subclasses, so we exclude it here.
2976 // We also want to avoid setting the flag on Object, where we know that finalize() is
2977 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002978 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2979 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002980 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002981 }
2982 }
2983 }
2984 } else if (method_name[0] == '<') {
2985 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002986 bool is_init = (strcmp("<init>", method_name) == 0);
2987 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002988 if (UNLIKELY(!is_init && !is_clinit)) {
2989 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2990 } else {
2991 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2992 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002993 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002994 access_flags |= kAccConstructor;
2995 }
2996 }
2997 }
2998 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002999
Mathieu Chartier66f19252012-09-18 08:57:04 -07003000 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07003001}
3002
Ian Rogers7b078e82014-09-10 14:44:24 -07003003void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003004 StackHandleScope<1> hs(self);
3005 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003006 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3007 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003008 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003009}
3010
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003011void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003012 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003013 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003014 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003015 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003016}
3017
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003018bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003019 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07003020 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003021 mirror::DexCache* dex_cache = GetDexCache(i);
3022 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08003023 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003024 }
3025 }
3026 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003027}
3028
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003029bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003030 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003031 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003032}
3033
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003034void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003035 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003036 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003037 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003038 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3039 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003040 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003041 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003042 if (log_new_dex_caches_roots_) {
3043 // TODO: This is not safe if we can remove dex caches.
3044 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3045 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003046}
3047
Brian Carlstromaded5f72011-10-07 17:15:04 -07003048void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003049 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003050 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003051 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003052 if (IsDexFileRegisteredLocked(dex_file)) {
3053 return;
3054 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003055 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003056 // Don't alloc while holding the lock, since allocation may need to
3057 // suspend all threads and another thread may need the dex_lock_ to
3058 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003059 StackHandleScope<1> hs(self);
3060 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003061 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3062 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003063 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003064 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003065 if (IsDexFileRegisteredLocked(dex_file)) {
3066 return;
3067 }
3068 RegisterDexFileLocked(dex_file, dex_cache);
3069 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003070}
3071
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003072void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003073 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003074 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003075 RegisterDexFileLocked(dex_file, dex_cache);
3076}
3077
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003078mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003079 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003080 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003081 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003082 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003083 if (dex_cache->GetDexFile() == &dex_file) {
3084 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003085 }
3086 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003087 // Search matching by location name.
3088 std::string location(dex_file.GetLocation());
3089 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003090 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003091 if (dex_cache->GetDexFile()->GetLocation() == location) {
3092 return dex_cache;
3093 }
3094 }
3095 // Failure, dump diagnostic and abort.
3096 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003097 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003098 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3099 }
3100 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003101 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003102}
3103
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003104void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003105 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003106 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003107 mirror::DexCache* dex_cache = GetDexCache(i);
3108 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003109 }
3110}
3111
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003112mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003113 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003114 if (UNLIKELY(klass == nullptr)) {
3115 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003116 }
3117 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003118}
3119
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003120mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3121 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003122 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003123 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003124 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003125 StackHandleScope<1> hs(self);
3126 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003127 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003128 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003129 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003130 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3131 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003132 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3133 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003134 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003135 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003136}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003137
Brian Carlstrombe977852011-07-19 14:54:54 -07003138// Create an array class (i.e. the class object for the array, not the
3139// array itself). "descriptor" looks like "[C" or "[[[[B" or
3140// "[Ljava/lang/String;".
3141//
3142// If "descriptor" refers to an array of primitives, look up the
3143// primitive type's internally-generated class object.
3144//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003145// "class_loader" is the class loader of the class that's referring to
3146// us. It's used to ensure that we're looking for the element type in
3147// the right context. It does NOT become the class loader for the
3148// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003149//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003150// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003151mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003152 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003153 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003154 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003155 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003156 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3157 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003158 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003159 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003160 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003161 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3162 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003163 if (component_type.Get() == nullptr) {
3164 DCHECK(self->IsExceptionPending());
3165 return nullptr;
3166 } else {
3167 self->ClearException();
3168 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003169 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003170 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3171 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3172 return nullptr;
3173 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003174 // See if the component type is already loaded. Array classes are
3175 // always associated with the class loader of their underlying
3176 // element type -- an array of Strings goes with the loader for
3177 // java/lang/String -- so we need to look for it there. (The
3178 // caller should have checked for the existence of the class
3179 // before calling here, but they did so with *their* class loader,
3180 // not the component type's loader.)
3181 //
3182 // If we find it, the caller adds "loader" to the class' initiating
3183 // loader list, which should prevent us from going through this again.
3184 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003185 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003186 // are the same, because our caller (FindClass) just did the
3187 // lookup. (Even if we get this wrong we still have correct behavior,
3188 // because we effectively do this lookup again when we add the new
3189 // class to the hash table --- necessary because of possible races with
3190 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003191 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003192 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003193 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003194 return new_class;
3195 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003196 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003197
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003198 // Fill out the fields in the Class.
3199 //
3200 // It is possible to execute some methods against arrays, because
3201 // all arrays are subclasses of java_lang_Object_, so we need to set
3202 // up a vtable. We can just point at the one in java_lang_Object_.
3203 //
3204 // Array classes are simple enough that we don't need to do a full
3205 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003206 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003207 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003208 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003209 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003210 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003211 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003212 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003213 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003214 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003215 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003216 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003217 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003218 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003219 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003220 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003221 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003222 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003223 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003224 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003225 }
3226 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003227 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003228 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003229 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003230 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003231 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003232 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003233 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003234 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003235 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003236 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003237 new_class->SetSuperClass(java_lang_Object);
3238 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003239 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003240 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003241 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003242 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003243 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3244 Runtime::Current()->GetImtUnimplementedMethod());
3245 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003246 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003247 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003248 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003249 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003250
3251
3252 // All arrays have java/lang/Cloneable and java/io/Serializable as
3253 // interfaces. We need to set that up here, so that stuff like
3254 // "instanceof" works right.
3255 //
3256 // Note: The GC could run during the call to FindSystemClass,
3257 // so we need to make sure the class object is GC-valid while we're in
3258 // there. Do this by clearing the interface list so the GC will just
3259 // think that the entries are null.
3260
3261
3262 // Use the single, global copies of "interfaces" and "iftable"
3263 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003264 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003265 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003266 CHECK(array_iftable != nullptr);
3267 new_class->SetIfTable(array_iftable);
3268 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003269
Elliott Hughes00626c22013-06-14 15:04:14 -07003270 // Inherit access flags from the component type.
3271 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3272 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3273 access_flags &= kAccJavaFlagsMask;
3274 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003275 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003276 access_flags |= kAccAbstract | kAccFinal;
3277 access_flags &= ~kAccInterface;
3278
3279 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003280
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003281 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003282 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003283 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003284 }
3285 // Another thread must have loaded the class after we
3286 // started but before we finished. Abandon what we've
3287 // done.
3288 //
3289 // (Yes, this happens.)
3290
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003291 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003292}
3293
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003294mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003295 switch (type) {
3296 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003297 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003298 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003299 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003300 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003301 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003302 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003303 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003304 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003305 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003306 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003307 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003308 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003309 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003310 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003311 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003312 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003313 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003314 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003315 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003316 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003317 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003318 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003319 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003320}
3321
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003322mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3323 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003324 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003325 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003326 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003327 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003328 source += " from ";
3329 source += dex_cache->GetLocation()->ToModifiedUtf8();
3330 }
3331 LOG(INFO) << "Loaded class " << descriptor << source;
3332 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003333 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003334 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003335 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003336 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003337 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003338 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003339 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003340 // Check a class loaded with the system class loader matches one in the image if the class
3341 // is in the image.
3342 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003343 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003344 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003345 }
3346 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003347 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003348 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003349 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003350 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003351 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003352 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003353}
3354
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003355mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3356 size_t hash) {
3357 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003358 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3359 hash);
3360 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003361 CHECK(klass->IsProxyClass());
3362 return nullptr;
3363 }
3364
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003365 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003366 CHECK_NE(existing, klass) << descriptor;
3367 CHECK(!existing->IsResolved()) << descriptor;
3368 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3369
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003370 CHECK(!klass->IsTemp()) << descriptor;
3371 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3372 dex_cache_image_class_lookup_required_) {
3373 // Check a class loaded with the system class loader matches one in the image if the class
3374 // is in the image.
3375 existing = LookupClassFromImage(descriptor);
3376 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003377 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003378 }
3379 }
3380 VerifyObject(klass);
3381
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003382 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003383 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003384 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003385 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003386 }
3387
3388 return existing;
3389}
3390
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003391bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003392 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003393 auto pair = std::make_pair(descriptor, class_loader);
3394 auto it = class_table_.Find(pair);
3395 if (it != class_table_.end()) {
3396 class_table_.Erase(it);
3397 return true;
3398 }
3399 it = pre_zygote_class_table_.Find(pair);
3400 if (it != pre_zygote_class_table_.end()) {
3401 pre_zygote_class_table_.Erase(it);
3402 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003403 }
3404 return false;
3405}
3406
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003407mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003408 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003409 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003410 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003411 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003412 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003413 return result;
3414 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003415 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003416 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3417 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003418 } else {
3419 // Lookup failed but need to search dex_caches_.
3420 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003421 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003422 InsertClass(descriptor, result, hash);
3423 } else {
3424 // Searching the image dex files/caches failed, we don't want to get into this situation
3425 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3426 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003427 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003428 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3429 MoveImageClassesToClassTable();
3430 }
3431 }
3432 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003433 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003434}
3435
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003436mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003437 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003438 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003439 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3440 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3441 if (it == pre_zygote_class_table_.end()) {
3442 it = class_table_.FindWithHash(descriptor_pair, hash);
3443 if (it == class_table_.end()) {
3444 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003445 }
3446 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003447 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003448}
3449
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003450static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3451 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3452 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003453 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003454 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3455 return root->AsObjectArray<mirror::DexCache>();
3456}
3457
3458void ClassLinker::MoveImageClassesToClassTable() {
3459 Thread* self = Thread::Current();
3460 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3461 if (!dex_cache_image_class_lookup_required_) {
3462 return; // All dex cache classes are already in the class table.
3463 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003464 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003465 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003466 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003467 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3468 mirror::DexCache* dex_cache = dex_caches->Get(i);
3469 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3470 for (int32_t j = 0; j < types->GetLength(); j++) {
3471 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003472 if (klass != nullptr) {
3473 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003474 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003475 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003476 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3477 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003478 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003479 << PrettyClassAndClassLoader(klass);
3480 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003481 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003482 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003483 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003484 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003485 }
3486 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003487 }
3488 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003489 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003490}
3491
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003492void ClassLinker::MoveClassTableToPreZygote() {
3493 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3494 DCHECK(pre_zygote_class_table_.Empty());
3495 pre_zygote_class_table_ = std::move(class_table_);
3496 class_table_.Clear();
3497}
3498
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003499mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003500 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003501 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3502 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3503 mirror::DexCache* dex_cache = dex_caches->Get(i);
3504 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003505 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003506 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003507 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003508 const DexFile::TypeId* type_id =
3509 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003510 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003511 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3512 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003513 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003514 return klass;
3515 }
3516 }
3517 }
3518 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003519 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003520}
3521
3522void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3523 result.clear();
3524 if (dex_cache_image_class_lookup_required_) {
3525 MoveImageClassesToClassTable();
3526 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003527 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3528 while (true) {
3529 auto it = class_table_.Find(descriptor);
3530 if (it == class_table_.end()) {
3531 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003532 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003533 result.push_back(it->Read());
3534 class_table_.Erase(it);
3535 }
3536 for (mirror::Class* k : result) {
3537 class_table_.Insert(GcRoot<mirror::Class>(k));
3538 }
3539 size_t pre_zygote_start = result.size();
3540 // Now handle the pre zygote table.
3541 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3542 // called from the debugger.
3543 while (true) {
3544 auto it = pre_zygote_class_table_.Find(descriptor);
3545 if (it == pre_zygote_class_table_.end()) {
3546 break;
3547 }
3548 result.push_back(it->Read());
3549 pre_zygote_class_table_.Erase(it);
3550 }
3551 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3552 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003553 }
3554}
3555
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003556void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003557 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003558 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003559
Ian Rogers9ffb0392012-09-10 11:56:50 -07003560 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003561 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003562 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003563 return;
3564 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003565 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3566 return;
3567 }
jeffhao98eacac2011-09-14 16:11:53 -07003568
Ian Rogers9ffb0392012-09-10 11:56:50 -07003569 // The class might already be erroneous, for example at compile time if we attempted to verify
3570 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003571 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003572 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003573 return;
3574 }
3575
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003576 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003577 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003578 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003579 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003580 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003581 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003582 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003583 }
jeffhao98eacac2011-09-14 16:11:53 -07003584
Jeff Hao4a200f52014-04-01 14:58:49 -07003585 // Skip verification if disabled.
3586 if (!Runtime::Current()->IsVerificationEnabled()) {
3587 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003588 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003589 return;
3590 }
3591
Ian Rogers9ffb0392012-09-10 11:56:50 -07003592 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003593 StackHandleScope<2> hs(self);
3594 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003595 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003596 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003597 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003598
3599 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003600 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003601 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003602 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003603 std::string error_msg(
3604 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3605 PrettyDescriptor(klass.Get()).c_str(),
3606 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003607 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003608 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3609 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003610 self->ClearException();
3611 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003612 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3613 if (cause.Get() != nullptr) {
3614 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003615 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003616 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003617 if (Runtime::Current()->IsCompiler()) {
3618 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3619 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003620 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003621 return;
3622 }
3623 }
3624
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003625 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003626 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003627 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003628 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003629 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003630 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003631 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003632 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003633 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3634 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003635 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003636 return;
3637 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003638 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003639 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003640 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003641 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003642 Runtime::Current()->IsCompiler(),
3643 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003644 }
3645 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003646 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003647 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003648 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3649 << " because: " << error_msg;
3650 }
Ian Rogers1f539342012-10-03 21:09:42 -07003651 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003652 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003653 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003654 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003655 // Even though there were no verifier failures we need to respect whether the super-class
3656 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003657 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003658 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003659 } else {
3660 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003661 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003662 // Pretend a soft failure occured so that we don't consider the class verified below.
3663 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003664 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003665 } else {
3666 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3667 // Soft failures at compile time should be retried at runtime. Soft
3668 // failures at runtime will be handled by slow paths in the generated
3669 // code. Set status accordingly.
3670 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003671 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003672 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003673 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003674 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3675 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003676 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003677 }
3678 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003679 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003680 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003681 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3682 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003683 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003684 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003685 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003686 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003687 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003688 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003689 // Let the interpreter know it by setting the kAccPreverified flag onto each
3690 // method.
3691 // Note: we're going here during compilation and at runtime. When we set the
3692 // kAccPreverified flag when compiling image classes, the flag is recorded
3693 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003694 EnsurePreverifiedMethods(klass);
3695 }
3696}
3697
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003698void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003699 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003700 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003701 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003702 }
jeffhao98eacac2011-09-14 16:11:53 -07003703}
3704
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003705bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3706 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003707 // If we're compiling, we can only verify the class using the oat file if
3708 // we are not compiling the image or if the class we're verifying is not part of
3709 // the app. In other words, we will only check for preverification of bootclasspath
3710 // classes.
3711 if (Runtime::Current()->IsCompiler()) {
3712 // Are we compiling the bootclasspath?
3713 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3714 return false;
3715 }
3716 // We are compiling an app (not the image).
3717
3718 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003719 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003720 return false;
3721 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003722 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003723
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003724 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003725 // In case we run without an image there won't be a backing oat file.
3726 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003727 return false;
3728 }
3729
Andreas Gampe76bd8802014-12-10 16:43:58 -08003730 // We may be running with a preopted oat file but without image. In this case,
3731 // we don't skip verification of preverified classes to ensure we initialize
3732 // dex caches with all types resolved during verification.
3733 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3734 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3735 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3736 // already pre-opted, as then the runtime is started.
3737 if (!Runtime::Current()->IsCompiler() &&
3738 !Runtime::Current()->GetHeap()->HasImageSpace() &&
3739 klass->GetClassLoader() != nullptr) {
3740 return false;
3741 }
3742
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003743 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003744 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003745 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3746 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003747 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003748 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003749 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003750 // Compile time verification failed with a soft error. Compile time verification can fail
3751 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003752 // class ... {
3753 // Foo x;
3754 // .... () {
3755 // if (...) {
3756 // v1 gets assigned a type of resolved class Foo
3757 // } else {
3758 // v1 gets assigned a type of unresolved class Bar
3759 // }
3760 // iput x = v1
3761 // } }
3762 // when we merge v1 following the if-the-else it results in Conflict
3763 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3764 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3765 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3766 // at compile time).
3767 return false;
3768 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003769 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003770 // Compile time verification failed with a hard error. This is caused by invalid instructions
3771 // in the class. These errors are unrecoverable.
3772 return false;
3773 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003774 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003775 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3776 // not loading the class.
3777 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3778 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003779 return false;
3780 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003781 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003782 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003783 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003784 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003785 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003786}
3787
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003788void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003789 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003790 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3791 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3792 }
3793 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3794 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3795 }
3796}
3797
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003798void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003799 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003800 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3801 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003802 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003803 return; // native or abstract method
3804 }
3805 if (code_item->tries_size_ == 0) {
3806 return; // nothing to process
3807 }
Ian Rogers13735952014-10-08 12:43:28 -07003808 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003809 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3810 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3811 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3812 CatchHandlerIterator iterator(handlers_ptr);
3813 for (; iterator.HasNext(); iterator.Next()) {
3814 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3815 // unresolved exception types will be ignored by exception delivery
3816 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003817 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003818 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003819 DCHECK(Thread::Current()->IsExceptionPending());
3820 Thread::Current()->ClearException();
3821 }
3822 }
3823 }
3824 handlers_ptr = iterator.EndDataPointer();
3825 }
3826}
3827
Brian Carlstromea46f952013-07-30 01:26:50 -07003828static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003829static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3830 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003831
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003832mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003833 jobjectArray interfaces, jobject loader,
3834 jobjectArray methods, jobjectArray throws) {
3835 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003836 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003837 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003838 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003839 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003840 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003841 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003842 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003843 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003844 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003845 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3846 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003847 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003848 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003849 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003850 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003851 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003852 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003853
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003854 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003855 {
3856 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003857 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003858 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003859 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003860 }
3861 klass->SetSFields(sfields);
3862 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003863 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3864 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003865 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3866 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003867 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003868 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003869 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003870 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003871 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003872 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003873 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3874 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003875 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3876 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003877 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003878 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003879 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003880 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003881 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003882 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003883 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003884
Ian Rogers466bb252011-10-14 03:29:56 -07003885 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003886 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003887 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003888 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003889 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003890 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003891 }
3892 klass->SetDirectMethods(directs);
3893 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003894 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003895 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003896 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003897 }
3898 klass->SetDirectMethod(0, constructor);
3899 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003900
Mathieu Chartier590fee92013-09-13 13:46:47 -07003901 // Create virtual method using specified prototypes.
3902 size_t num_virtual_methods =
3903 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003904 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003905 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3906 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003907 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003908 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003909 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003910 }
3911 klass->SetVirtualMethods(virtuals);
3912 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003913 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003914 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003915 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3916 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003917 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003918 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003919 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003920 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003921 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003922 }
3923 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003924 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003925
3926 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003927 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003928 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003929
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003930 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3931 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003932 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003933 // Must hold lock on object when resolved.
3934 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003935 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003936 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003937 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003938 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003939 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003940 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003941 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003942 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003943
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003944 CHECK(klass->IsRetired());
3945 CHECK_NE(klass.Get(), new_class);
3946 klass.Assign(new_class);
3947
3948 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003949 interfaces_sfield->SetObject<false>(klass.Get(),
3950 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003951 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003952 throws_sfield->SetObject<false>(klass.Get(),
3953 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003954
3955 {
3956 // Lock on klass is released. Lock new class object.
3957 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003958 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003959 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003960
3961 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003962 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003963 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003964 CheckProxyConstructor(klass->GetDirectMethod(0));
3965 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003966 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003967 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3968 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003969 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3970 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003971 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003972 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003973
Mathieu Chartier590fee92013-09-13 13:46:47 -07003974 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003975 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003976 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003977 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3978
3979 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003980 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003981 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003982
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003983 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003984 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003985 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003986 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003987 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003988 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3989 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003990 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003991 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003992}
3993
Ian Rogersef7d42f2014-01-06 12:55:46 -08003994std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003995 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003996 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003997 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003998 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3999}
4000
Ian Rogersef7d42f2014-01-06 12:55:46 -08004001mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
4002 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08004003 DCHECK(proxy_class->IsProxyClass());
4004 DCHECK(proxy_method->IsProxyMethod());
4005 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07004006 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08004007 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07004008 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08004009 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004010 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07004011 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07004012 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08004013 break;
4014 }
4015 }
4016 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07004017 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08004018 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07004019 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07004020 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08004021 return resolved_method;
4022}
4023
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004024
Brian Carlstromea46f952013-07-30 01:26:50 -07004025mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004026 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07004027 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07004028 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07004029 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004030 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07004031 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
4032 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02004033 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4034 // constructor method.
4035 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
4036 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07004037 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4038 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07004039 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
4040 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004041 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07004042 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004043 }
Ian Rogers466bb252011-10-14 03:29:56 -07004044 // Make this constructor public and fix the class to be our Proxy version
4045 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004046 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004047 return constructor;
4048}
4049
Brian Carlstromea46f952013-07-30 01:26:50 -07004050static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004051 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004052 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004053 CHECK_STREQ(constructor->GetName(), "<init>");
4054 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4055 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004056 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004057}
4058
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004059mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004060 Handle<mirror::Class> klass,
4061 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004062 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4063 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004064 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004065 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004066 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004067 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004068 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004069 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004070 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004071 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004072 }
Ian Rogers466bb252011-10-14 03:29:56 -07004073
4074 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4075 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004076 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004077 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004078
Ian Rogers466bb252011-10-14 03:29:56 -07004079 // At runtime the method looks like a reference and argument saving method, clone the code
4080 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004081 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4082 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004083 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004084
Ian Rogersc2b44472011-12-14 21:17:17 -08004085 return method;
4086}
Jesse Wilson95caa792011-10-12 18:14:17 -04004087
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004088static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4089 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004090 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004091 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004092 CHECK(!prototype->IsFinal());
4093 CHECK(method->IsFinal());
4094 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004095
4096 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4097 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07004098 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4099 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004100 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4101
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004102 CHECK_STREQ(method->GetName(), prototype->GetName());
4103 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004104 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004105 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004106}
4107
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004108static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4109 bool can_init_parents)
4110 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004111 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004112 return true;
4113 }
4114 if (!can_init_statics) {
4115 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004116 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004117 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004118 return false;
4119 }
4120 // Check if there are encoded static values needing initialization.
4121 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004122 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004123 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004124 if (dex_class_def->static_values_off_ != 0) {
4125 return false;
4126 }
4127 }
4128 }
4129 if (!klass->IsInterface() && klass->HasSuperClass()) {
4130 mirror::Class* super_class = klass->GetSuperClass();
4131 if (!can_init_parents && !super_class->IsInitialized()) {
4132 return false;
4133 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004134 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004135 return false;
4136 }
4137 }
4138 }
4139 return true;
4140}
4141
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004142bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004143 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004144 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4145
4146 // Are we already initialized and therefore done?
4147 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4148 // an initialized class will never change its state.
4149 if (klass->IsInitialized()) {
4150 return true;
4151 }
4152
4153 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004154 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004155 return false;
4156 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004157
Ian Rogers7b078e82014-09-10 14:44:24 -07004158 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004159 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004160 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004161 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004162
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004163 // Re-check under the lock in case another thread initialized ahead of us.
4164 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004165 return true;
4166 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004167
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004168 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004169 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004170 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004171 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004172 return false;
4173 }
4174
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004175 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004176
4177 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004178 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004179 if (!klass->IsVerified()) {
4180 // We failed to verify, expect either the klass to be erroneous or verification failed at
4181 // compile time.
4182 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004183 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004184 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004185 } else {
4186 CHECK(Runtime::Current()->IsCompiler());
4187 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004188 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004189 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004190 } else {
4191 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004192 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004193 }
4194
Brian Carlstromd1422f82011-09-28 11:37:09 -07004195 // If the class is kStatusInitializing, either this thread is
4196 // initializing higher up the stack or another thread has beat us
4197 // to initializing and we need to wait. Either way, this
4198 // invocation of InitializeClass will not be responsible for
4199 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004200 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004201 // Could have got an exception during verification.
4202 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004203 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004204 return false;
4205 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004206 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004207 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004208 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004209 return true;
4210 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004211 // No. That's fine. Wait for another thread to finish initializing.
4212 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004213 }
4214
4215 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004216 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004217 return false;
4218 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004219 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004220
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004221 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004222
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004223 // From here out other threads may observe that we're initializing and so changes of state
4224 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004225 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004226 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004227
4228 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004229 }
4230
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004231 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004232 if (!klass->IsInterface() && klass->HasSuperClass()) {
4233 mirror::Class* super_class = klass->GetSuperClass();
4234 if (!super_class->IsInitialized()) {
4235 CHECK(!super_class->IsInterface());
4236 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004237 StackHandleScope<1> hs(self);
4238 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004239 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004240 if (!super_initialized) {
4241 // The super class was verified ahead of entering initializing, we should only be here if
4242 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004243 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004244 << "Super class initialization failed for "
4245 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004246 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004247 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004248 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004249 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004250 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004251 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004252 return false;
4253 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004254 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004255 }
4256
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004257 const size_t num_static_fields = klass->NumStaticFields();
4258 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004259 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004260 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004261 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004262 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004263 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004264 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004265
4266 // Eagerly fill in static fields so that the we don't have to do as many expensive
4267 // Class::FindStaticField in ResolveField.
4268 for (size_t i = 0; i < num_static_fields; ++i) {
4269 mirror::ArtField* field = klass->GetStaticField(i);
4270 const uint32_t field_idx = field->GetDexFieldIndex();
4271 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4272 if (resolved_field == nullptr) {
4273 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004274 } else {
4275 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004276 }
4277 }
4278
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004279 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4280 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004281 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004282 ClassDataItemIterator field_it(dex_file, class_data);
4283 if (value_it.HasNext()) {
4284 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004285 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004286 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004287 StackHandleScope<1> hs2(self);
4288 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004289 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004290 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004291 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004292 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004293 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004294 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004295 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004296 }
4297 }
4298 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004299
Ian Rogersd91d6d62013-09-25 20:26:14 -07004300 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004301 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004302 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004303 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004304 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004305 }
4306
Ian Rogers7b078e82014-09-10 14:44:24 -07004307 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004308 uint64_t t1 = NanoTime();
4309
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004310 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004311 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004312 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004313
4314 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004315 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004316 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004317 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004318 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004319 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4320 RuntimeStats* thread_stats = self->GetStats();
4321 ++global_stats->class_init_count;
4322 ++thread_stats->class_init_count;
4323 global_stats->class_init_time_ns += (t1 - t0);
4324 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004325 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004326 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004327 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004328 std::string temp;
4329 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004330 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004331 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004332 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004333 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004334 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004335 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004336 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004337}
4338
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004339bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004340 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004341 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004342 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004343 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004344 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004345 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004346
4347 // When we wake up, repeat the test for init-in-progress. If
4348 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004349 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004350 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004351 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004352 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004353 return false;
4354 }
4355 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004356 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004357 continue;
4358 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004359 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004360 // Compile time initialization failed.
4361 return false;
4362 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004363 if (klass->IsErroneous()) {
4364 // The caller wants an exception, but it was thrown in a
4365 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004366 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004367 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004368 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004369 return false;
4370 }
4371 if (klass->IsInitialized()) {
4372 return true;
4373 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004374 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004375 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004376 }
Ian Rogers07140832014-09-30 15:43:59 -07004377 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004378}
4379
Ian Rogersb5fb2072014-12-02 17:22:02 -08004380static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4381 Handle<mirror::ArtMethod> method1,
4382 Handle<mirror::ArtMethod> method2)
4383 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4384 {
4385 StackHandleScope<1> hs(self);
4386 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
4387 if (UNLIKELY(method2->GetReturnType() != return_type.Get())) {
4388 return false;
4389 }
4390 }
4391 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4392 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4393 if (types1 == nullptr) {
4394 return (types2 == nullptr) || (types2->Size() == 0);
4395 } else if (UNLIKELY(types2 == nullptr)) {
4396 return types1->Size() == 0;
4397 }
4398 uint32_t num_types = types1->Size();
4399 if (UNLIKELY(num_types != types2->Size())) {
4400 return false;
4401 }
4402 for (uint32_t i = 0; i < num_types; ++i) {
4403 mirror::Class* param_type =
4404 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true);
4405 mirror::Class* other_param_type =
4406 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
4407 if (UNLIKELY(param_type != other_param_type)) {
4408 return false;
4409 }
4410 }
4411 return true;
4412}
4413
4414
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004415bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004416 if (klass->IsInterface()) {
4417 return true;
4418 }
Ian Rogers151f2212014-05-06 11:27:27 -07004419 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004420 Thread* self = Thread::Current();
4421 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004422 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
4423 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004424 if (klass->HasSuperClass() &&
4425 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004426 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004427 h_m.Assign(klass->GetVTableEntry(i));
4428 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
4429 if (h_m.Get() != super_h_m.Get() &&
4430 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004431 ThrowLinkageError(klass.Get(),
4432 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004433 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004434 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004435 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004436 return false;
4437 }
4438 }
4439 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004440 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004441 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4442 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4443 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004444 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4445 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
4446 if (h_m.Get() != super_h_m.Get() &&
4447 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004448 ThrowLinkageError(klass.Get(),
4449 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004450 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004451 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004452 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004453 return false;
4454 }
4455 }
4456 }
4457 }
4458 return true;
4459}
4460
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004461bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4462 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004463 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004464 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004465 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004466 return true;
4467 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004468 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004469 if (!success) {
4470 if (can_init_fields && can_init_parents) {
4471 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4472 }
4473 } else {
4474 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004475 }
4476 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004477}
4478
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004479void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4480 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4481 if (fields != nullptr) {
4482 for (int index = 0; index < fields->GetLength(); index ++) {
4483 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4484 fields->Get(index)->SetDeclaringClass(new_class);
4485 }
4486 }
4487 }
4488
4489 fields = new_class->GetSFields();
4490 if (fields != nullptr) {
4491 for (int index = 0; index < fields->GetLength(); index ++) {
4492 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4493 fields->Get(index)->SetDeclaringClass(new_class);
4494 }
4495 }
4496 }
4497
4498 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4499 if (methods != nullptr) {
4500 for (int index = 0; index < methods->GetLength(); index ++) {
4501 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4502 methods->Get(index)->SetDeclaringClass(new_class);
4503 }
4504 }
4505 }
4506
4507 methods = new_class->GetVirtualMethods();
4508 if (methods != nullptr) {
4509 for (int index = 0; index < methods->GetLength(); index ++) {
4510 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4511 methods->Get(index)->SetDeclaringClass(new_class);
4512 }
4513 }
4514 }
4515}
4516
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004517bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4518 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004519 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004520 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004521
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004522 if (!LinkSuperClass(klass)) {
4523 return false;
4524 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004525 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4526 self, Runtime::Current()->GetImtUnimplementedMethod());
4527 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004528 return false;
4529 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004530 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004531 return false;
4532 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004533 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004534 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004535 return false;
4536 }
4537 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004538 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004539
4540 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4541 // We don't need to retire this class as it has no embedded tables or it was created the
4542 // correct size during class linker initialization.
4543 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4544
4545 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004546 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004547 }
4548
4549 // This will notify waiters on klass that saw the not yet resolved
4550 // class in the class_table_ during EnsureResolved.
4551 klass->SetStatus(mirror::Class::kStatusResolved, self);
4552 *new_class = klass.Get();
4553 } else {
4554 CHECK(!klass->IsResolved());
4555 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004556 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004557 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004558 CHECK(self->IsExceptionPending()); // Expect an OOME.
4559 klass->SetStatus(mirror::Class::kStatusError, self);
4560 return false;
4561 }
4562
4563 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4564 StackHandleScope<1> hs(self);
4565 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4566 ObjectLock<mirror::Class> lock(self, new_class_h);
4567
4568 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4569
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004570 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4571 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004572 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004573
4574 // This will notify waiters on temp class that saw the not yet resolved class in the
4575 // class_table_ during EnsureResolved.
4576 klass->SetStatus(mirror::Class::kStatusRetired, self);
4577
4578 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4579 // This will notify waiters on new_class that saw the not yet resolved
4580 // class in the class_table_ during EnsureResolved.
4581 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004582 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004583 return true;
4584}
4585
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004586bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004587 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004588 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4589 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004590 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004591 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004592 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004593 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004594 return false;
4595 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004596 // Verify
4597 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004598 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004599 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004600 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004601 return false;
4602 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004603 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004604 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004605 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004606 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004607 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004608 for (size_t i = 0; i < interfaces->Size(); i++) {
4609 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004610 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004611 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004612 DCHECK(Thread::Current()->IsExceptionPending());
4613 return false;
4614 }
4615 // Verify
4616 if (!klass->CanAccess(interface)) {
4617 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004618 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004619 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004620 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004621 return false;
4622 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004623 }
4624 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004625 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004626 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004627 return true;
4628}
4629
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004630bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004631 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004632 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004633 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004634 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004635 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004636 return false;
4637 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004638 return true;
4639 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004640 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004641 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4642 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004643 return false;
4644 }
4645 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004646 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004647 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004648 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004649 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004650 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004651 return false;
4652 }
4653 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004654 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004655 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004656 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004657 return false;
4658 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004659
Brian Carlstromf3632832014-05-20 15:36:53 -07004660 // Inherit kAccClassIsFinalizable from the superclass in case this
4661 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004662 if (super->IsFinalizable()) {
4663 klass->SetFinalizable();
4664 }
4665
Elliott Hughes2da50362011-10-10 16:57:08 -07004666 // Inherit reference flags (if any) from the superclass.
4667 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4668 if (reference_flags != 0) {
4669 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4670 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004671 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004672 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004673 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004674 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004675 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004676 return false;
4677 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004678
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004679 if (kIsDebugBuild) {
4680 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004681 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004682 CHECK(super->IsResolved());
4683 super = super->GetSuperClass();
4684 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004685 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004686 return true;
4687}
4688
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004689// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004690bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004691 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4692 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004693 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004694 if (klass->IsInterface()) {
4695 // No vtable.
4696 size_t count = klass->NumVirtualMethods();
4697 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004698 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004699 return false;
4700 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004701 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004702 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004703 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004704 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4705 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004706 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004707 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004708}
4709
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004710// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4711// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4712// caches in the implementation below.
4713class MethodNameAndSignatureComparator FINAL : public ValueObject {
4714 public:
4715 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4716 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4717 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4718 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004719 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4720 }
4721
4722 const char* GetName() {
4723 if (name_ == nullptr) {
4724 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4725 }
4726 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004727 }
4728
4729 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4730 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4731 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4732 const DexFile* other_dex_file = other->GetDexFile();
4733 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4734 if (dex_file_ == other_dex_file) {
4735 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4736 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004737 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004738 uint32_t other_name_len;
4739 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4740 &other_name_len);
4741 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4742 return false;
4743 }
4744 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4745 }
4746
4747 private:
4748 // Dex file for the method to compare against.
4749 const DexFile* const dex_file_;
4750 // MethodId for the method to compare against.
4751 const DexFile::MethodId* const mid_;
4752 // Lazily computed name from the dex file's strings.
4753 const char* name_;
4754 // Lazily computed name length.
4755 uint32_t name_len_;
4756};
4757
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004758class LinkVirtualHashTable {
4759 public:
4760 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4761 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4762 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4763 }
4764 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4765 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4766 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004767 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004768 uint32_t index = hash % hash_size_;
4769 // Linear probe until we have an empty slot.
4770 while (hash_table_[index] != invalid_index_) {
4771 if (++index == hash_size_) {
4772 index = 0;
4773 }
4774 }
4775 hash_table_[index] = virtual_method_index;
4776 }
4777 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4778 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4779 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004780 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004781 size_t index = hash % hash_size_;
4782 while (true) {
4783 const uint32_t value = hash_table_[index];
4784 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4785 // the block and can safely assume not found.
4786 if (value == invalid_index_) {
4787 break;
4788 }
4789 if (value != removed_index_) { // This signifies not already overriden.
4790 mirror::ArtMethod* virtual_method =
4791 klass_->GetVirtualMethodDuringLinking(value);
4792 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4793 hash_table_[index] = removed_index_;
4794 return value;
4795 }
4796 }
4797 if (++index == hash_size_) {
4798 index = 0;
4799 }
4800 }
4801 return GetNotFoundIndex();
4802 }
4803 static uint32_t GetNotFoundIndex() {
4804 return invalid_index_;
4805 }
4806
4807 private:
4808 static const uint32_t invalid_index_;
4809 static const uint32_t removed_index_;
4810
4811 Handle<mirror::Class> klass_;
4812 const size_t hash_size_;
4813 uint32_t* const hash_table_;
4814};
4815
4816const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4817const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4818
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004819bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004820 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004821 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004822 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4823 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004824 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004825 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004826 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004827 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4828 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4829 if (UNLIKELY(vtable.Get() == nullptr)) {
4830 CHECK(self->IsExceptionPending()); // OOME.
4831 return false;
4832 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004833 for (size_t i = 0; i < super_vtable_length; i++) {
4834 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004835 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004836 if (num_virtual_methods == 0) {
4837 klass->SetVTable(vtable.Get());
4838 return true;
4839 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004840 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004841 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4842 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4843 if (num_virtual_methods == 0) {
4844 klass->SetVTable(super_vtable);
4845 return true;
4846 }
4847 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004848 if (UNLIKELY(vtable.Get() == nullptr)) {
4849 CHECK(self->IsExceptionPending()); // OOME.
4850 return false;
4851 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004852 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004853 // How the algorithm works:
4854 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4855 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4856 // method which has not been matched to a vtable method, and j if the virtual method at the
4857 // index overrode the super virtual method at index j.
4858 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4859 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4860 // the need for the initial vtable which we later shrink back down).
4861 // 3. Add non overridden methods to the end of the vtable.
4862 static constexpr size_t kMaxStackHash = 250;
4863 const size_t hash_table_size = num_virtual_methods * 3;
4864 uint32_t* hash_table_ptr;
4865 std::unique_ptr<uint32_t[]> hash_heap_storage;
4866 if (hash_table_size <= kMaxStackHash) {
4867 hash_table_ptr = reinterpret_cast<uint32_t*>(
4868 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4869 } else {
4870 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4871 hash_table_ptr = hash_heap_storage.get();
4872 }
4873 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4874 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004875 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004876 hash_table.Add(i);
4877 }
4878 // Loop through each super vtable method and see if they are overriden by a method we added to
4879 // the hash table.
4880 for (size_t j = 0; j < super_vtable_length; ++j) {
4881 // Search the hash table to see if we are overidden by any method.
4882 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4883 MethodNameAndSignatureComparator super_method_name_comparator(
4884 super_method->GetInterfaceMethodIfProxy());
4885 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4886 if (hash_index != hash_table.GetNotFoundIndex()) {
4887 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4888 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4889 super_method->GetAccessFlags())) {
4890 if (super_method->IsFinal()) {
4891 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4892 PrettyMethod(virtual_method).c_str(),
4893 super_method->GetDeclaringClassDescriptor());
4894 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004895 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004896 vtable->SetWithoutChecks<false>(j, virtual_method);
4897 virtual_method->SetMethodIndex(j);
4898 } else {
4899 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004900 << " would have incorrectly overridden the package-private method in "
4901 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004902 }
4903 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004904 }
4905 // Add the non overridden methods at the end.
4906 size_t actual_count = super_vtable_length;
4907 for (size_t i = 0; i < num_virtual_methods; ++i) {
4908 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4909 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4910 if (method_idx < super_vtable_length &&
4911 local_method == vtable->GetWithoutChecks(method_idx)) {
4912 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004913 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004914 vtable->SetWithoutChecks<false>(actual_count, local_method);
4915 local_method->SetMethodIndex(actual_count);
4916 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004917 }
4918 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004919 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004920 return false;
4921 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004922 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004923 CHECK_LE(actual_count, max_count);
4924 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004925 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004926 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004927 CHECK(self->IsExceptionPending()); // OOME.
4928 return false;
4929 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004930 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004931 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004932 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004933 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004934 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004935 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4936 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004937 return false;
4938 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004939 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4940 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004941 CHECK(self->IsExceptionPending()); // OOME.
4942 return false;
4943 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004944 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004945 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004946 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004947 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004948 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004949 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004950 }
4951 return true;
4952}
4953
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004954bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4955 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4956 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004957 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004958 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004959 const bool has_superclass = klass->HasSuperClass();
4960 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4961 const bool have_interfaces = interfaces.Get() != nullptr;
4962 const size_t num_interfaces =
4963 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4964 if (num_interfaces == 0) {
4965 if (super_ifcount == 0) {
4966 // Class implements no interfaces.
4967 DCHECK_EQ(klass->GetIfTableCount(), 0);
4968 DCHECK(klass->GetIfTable() == nullptr);
4969 return true;
4970 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004971 // Class implements same interfaces as parent, are any of these not marker interfaces?
4972 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004973 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004974 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004975 if (super_iftable->GetMethodArrayCount(i) > 0) {
4976 has_non_marker_interface = true;
4977 break;
4978 }
4979 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004980 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004981 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004982 klass->SetIfTable(super_iftable);
4983 return true;
4984 }
4985 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004986 size_t ifcount = super_ifcount + num_interfaces;
4987 for (size_t i = 0; i < num_interfaces; i++) {
4988 mirror::Class* interface = have_interfaces ?
4989 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4990 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004991 if (UNLIKELY(!interface->IsInterface())) {
4992 std::string temp;
4993 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4994 PrettyDescriptor(klass.Get()).c_str(),
4995 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4996 return false;
4997 }
4998 ifcount += interface->GetIfTableCount();
4999 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005000 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005001 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005002 CHECK(self->IsExceptionPending()); // OOME.
5003 return false;
5004 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005005 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005006 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005007 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005008 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07005009 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005010 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005011 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005012 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005013 // Flatten the interface inheritance hierarchy.
5014 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005015 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07005016 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
5017 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005018 // Check if interface is already in iftable
5019 bool duplicate = false;
5020 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005021 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005022 if (existing_interface == interface) {
5023 duplicate = true;
5024 break;
5025 }
5026 }
5027 if (!duplicate) {
5028 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07005029 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005030 // Add this interface's non-duplicate super-interfaces.
5031 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005032 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005033 bool super_duplicate = false;
5034 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005035 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005036 if (existing_interface == super_interface) {
5037 super_duplicate = true;
5038 break;
5039 }
5040 }
5041 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005042 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005043 }
5044 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005045 }
5046 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005047 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08005048 // Shrink iftable in case duplicates were found
5049 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005050 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005051 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005052 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005053 CHECK(self->IsExceptionPending()); // OOME.
5054 return false;
5055 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005056 ifcount = idx;
5057 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005058 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005059 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005060 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07005061 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005062 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005063 return true;
5064 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005065 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005066 size_t max_miranda_methods = 0; // The max size of miranda_list.
5067 for (size_t i = 0; i < ifcount; ++i) {
5068 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
5069 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005070 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005071 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005072 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5073 hs.NewHandle(klass->GetVTableDuringLinking()));
5074 // Copy the IMT from the super class if possible.
5075 bool extend_super_iftable = false;
5076 if (has_superclass) {
5077 mirror::Class* super_class = klass->GetSuperClass();
5078 extend_super_iftable = true;
5079 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5080 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5081 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5082 }
5083 } else {
5084 // No imt in the super class, need to reconstruct from the iftable.
5085 mirror::IfTable* if_table = super_class->GetIfTable();
5086 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5087 const size_t length = super_class->GetIfTableCount();
5088 for (size_t i = 0; i < length; ++i) {
5089 mirror::Class* interface = iftable->GetInterface(i);
5090 const size_t num_virtuals = interface->NumVirtualMethods();
5091 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5092 DCHECK_EQ(num_virtuals, method_array_count);
5093 if (method_array_count == 0) {
5094 continue;
5095 }
5096 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5097 for (size_t j = 0; j < num_virtuals; ++j) {
5098 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5099 if (method->IsMiranda()) {
5100 continue;
5101 }
5102 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5103 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5104 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5105 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5106 out_imt->SetReference(imt_index, method);
5107 } else if (imt_ref != conflict_method) {
5108 out_imt->SetReference(imt_index, conflict_method);
5109 }
5110 }
5111 }
5112 }
5113 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005114 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005115 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005116 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005117 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005118 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005119 const bool is_super = i < super_ifcount;
5120 const bool super_interface = is_super && extend_super_iftable;
5121 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5122 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5123 if (super_interface) {
5124 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5125 DCHECK(if_table != nullptr);
5126 DCHECK(if_table->GetMethodArray(i) != nullptr);
5127 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005128 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005129 AsObjectArray<mirror::ArtMethod>());
5130 // We are overwriting a super class interface, try to only virtual methods instead of the
5131 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005132 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005133 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005134 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005135 // A new interface, we need the whole vtable incase a new interface method is implemented
5136 // in the whole superclass.
5137 input_array = vtable;
5138 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005139 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005140 CHECK(self->IsExceptionPending()); // OOME.
5141 return false;
5142 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005143 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005144 if (input_array.Get() == nullptr) {
5145 // If the added virtual methods is empty, do nothing.
5146 DCHECK(super_interface);
5147 continue;
5148 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005149 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005150 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005151 MethodNameAndSignatureComparator interface_name_comparator(
5152 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005153 int32_t k;
5154 // For each method listed in the interface's method list, find the
5155 // matching method in our class's method list. We want to favor the
5156 // subclass over the superclass, which just requires walking
5157 // back from the end of the vtable. (This only matters if the
5158 // superclass defines a private method and this class redefines
5159 // it -- otherwise it would use the same vtable slot. In .dex files
5160 // those don't end up in the virtual method table, so it shouldn't
5161 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005162 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5163 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005164 mirror::ArtMethod* vtable_method_for_name_comparison =
5165 vtable_method->GetInterfaceMethodIfProxy();
5166 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005167 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005168 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005169 ThrowIllegalAccessError(
5170 klass.Get(),
5171 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005172 PrettyMethod(vtable_method).c_str(),
5173 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005174 return false;
5175 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005176 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005177 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005178 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5179 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5180 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5181 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5182 out_imt->SetReference(imt_index, vtable_method);
5183 } else if (imt_ref != conflict_method) {
5184 // If we are not a conflict and we have the same signature and name as the imt entry,
5185 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005186 MethodNameAndSignatureComparator imt_ref_name_comparator(
5187 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005188 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005189 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005190 out_imt->SetReference(imt_index, vtable_method);
5191 } else {
5192 out_imt->SetReference(imt_index, conflict_method);
5193 }
Jeff Hao88474b42013-10-23 16:24:40 -07005194 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005195 break;
5196 }
5197 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005198 if (k < 0 && !super_interface) {
5199 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005200 for (size_t l = 0; l < miranda_list_size; ++l) {
5201 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005202 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005203 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005204 break;
5205 }
5206 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005207 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005208 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005209 miranda_method = interface_method->Clone(self)->AsArtMethod();
5210 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005211 CHECK(self->IsExceptionPending()); // OOME.
5212 return false;
5213 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005214 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005215 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005216 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005217 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005218 }
5219 }
5220 }
5221 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005222 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005223 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005224 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005225 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5226 if (old_method_count == 0) {
5227 virtuals = AllocArtMethodArray(self, new_method_count);
5228 } else {
5229 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5230 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005231 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005232 CHECK(self->IsExceptionPending()); // OOME.
5233 return false;
5234 }
5235 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005236
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005237 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005238 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005239 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005240 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005241 CHECK(self->IsExceptionPending()); // OOME.
5242 return false;
5243 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005244 for (size_t i = 0; i < miranda_list_size; ++i) {
5245 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005246 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005247 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5248 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5249 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005250 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005251 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005252 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005253 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005254 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005255
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005256 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005257 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5258 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5259 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005260 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005261 }
5262
Ian Rogers7b078e82014-09-10 14:44:24 -07005263 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005264 return true;
5265}
5266
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005267bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005268 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005269 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005270}
5271
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005272bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005273 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005274 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005275}
5276
Brian Carlstromdbc05252011-09-09 01:59:59 -07005277struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005278 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5279 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005280 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005281 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005282 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005283 // 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 -07005284 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5285 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005286 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005287 if (type1 == Primitive::kPrimNot) {
5288 // Reference always goes first.
5289 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005290 }
Vladimir Markod5777482014-11-12 17:02:02 +00005291 if (type2 == Primitive::kPrimNot) {
5292 // Reference always goes first.
5293 return false;
5294 }
5295 size_t size1 = Primitive::ComponentSize(type1);
5296 size_t size2 = Primitive::ComponentSize(type2);
5297 if (size1 != size2) {
5298 // Larger primitive types go first.
5299 return size1 > size2;
5300 }
5301 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5302 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005303 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005304 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5305 // by name and for equal names by type id index.
5306 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5307 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005308 }
5309};
5310
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005311bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005312 size_t* class_size) {
5313 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005314 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005315 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005316
Brian Carlstromea46f952013-07-30 01:26:50 -07005317 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005318 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005319
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005320 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005321 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005322 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005323 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005324 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005325 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005326 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005327 CHECK(super_class->IsResolved())
5328 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005329 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005330 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005331 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005332
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005333 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005334
Brian Carlstromdbc05252011-09-09 01:59:59 -07005335 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005336 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005337 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005338 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005339 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005340 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005341 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005342 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005343 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005344 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005345 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5346 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005347
Fred Shih381e4ca2014-08-25 17:24:27 -07005348 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005349 size_t current_field = 0;
5350 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005351 FieldGaps gaps;
5352
Brian Carlstromdbc05252011-09-09 01:59:59 -07005353 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005354 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005355 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005356 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005357 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005358 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005359 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005360 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5361 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005362 MemberOffset old_offset = field_offset;
5363 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5364 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5365 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005366 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005367 grouped_and_sorted_fields.pop_front();
5368 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005369 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005370 field_offset = MemberOffset(field_offset.Uint32Value() +
5371 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005372 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005373 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5374 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005375 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5376 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5377 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5378 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005379 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5380 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005381 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005382
Elliott Hughesadb460d2011-10-05 17:02:34 -07005383 // 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 -07005384 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005385 // We know there are no non-reference fields in the Reference classes, and we know
5386 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005387 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005388 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005389 --num_reference_fields;
5390 }
5391
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005392 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005393 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005394 if (is_static) {
5395 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005396 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005397 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005398 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005399 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005400 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
5401 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
5402 } else {
5403 std::string temp;
5404 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5405 size_t previous_size = klass->GetObjectSize();
5406 if (previous_size != 0) {
5407 // Make sure that we didn't originally have an incorrect size.
5408 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5409 }
5410 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005411 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005412 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005413 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005414
5415 if (kIsDebugBuild) {
5416 // Make sure that the fields array is ordered by name but all reference
5417 // offsets are at the beginning as far as alignment allows.
5418 MemberOffset start_ref_offset = is_static
5419 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5420 : klass->GetFirstReferenceInstanceFieldOffset();
5421 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5422 num_reference_fields *
5423 sizeof(mirror::HeapReference<mirror::Object>));
5424 MemberOffset current_ref_offset = start_ref_offset;
5425 for (size_t i = 0; i < num_fields; i++) {
5426 mirror::ArtField* field = fields->Get(i);
5427 if ((false)) { // enable to debug field layout
5428 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5429 << " class=" << PrettyClass(klass.Get())
5430 << " field=" << PrettyField(field)
5431 << " offset="
5432 << field->GetField32(mirror::ArtField::OffsetOffset());
5433 }
5434 if (i != 0) {
5435 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005436 // NOTE: The field names can be the same. This is not possible in the Java language
5437 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5438 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005439 }
5440 Primitive::Type type = field->GetTypeAsPrimitiveType();
5441 bool is_primitive = type != Primitive::kPrimNot;
5442 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5443 strcmp("referent", field->GetName()) == 0) {
5444 is_primitive = true; // We lied above, so we have to expect a lie here.
5445 }
5446 MemberOffset offset = field->GetOffsetDuringLinking();
5447 if (is_primitive) {
5448 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5449 // Shuffled before references.
5450 size_t type_size = Primitive::ComponentSize(type);
5451 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5452 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5453 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5454 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5455 }
5456 } else {
5457 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5458 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5459 sizeof(mirror::HeapReference<mirror::Object>));
5460 }
5461 }
5462 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5463 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005464 return true;
5465}
5466
Vladimir Marko76649e82014-11-10 18:32:59 +00005467// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005468void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005469 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005470 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005471 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005472 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005473 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005474 // Compute reference offsets unless our superclass overflowed.
5475 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5476 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005477 if (num_reference_fields != 0u) {
5478 // All of the fields that contain object references are guaranteed be grouped in memory
5479 // starting at an appropriately aligned address after super class object data.
5480 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5481 sizeof(mirror::HeapReference<mirror::Object>));
5482 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005483 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005484 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005485 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005486 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005487 reference_offsets |= (0xffffffffu << start_bit) &
5488 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005489 }
5490 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005491 }
5492 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005493 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005494}
5495
Mathieu Chartier590fee92013-09-13 13:46:47 -07005496mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005497 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005498 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005499 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005500 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005501 return resolved;
5502 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005503 uint32_t utf16_length;
5504 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005505 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005506 dex_cache->SetResolvedString(string_idx, string);
5507 return string;
5508}
5509
Mathieu Chartier590fee92013-09-13 13:46:47 -07005510mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005511 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005512 StackHandleScope<2> hs(Thread::Current());
5513 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5514 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005515 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5516}
5517
5518mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005519 Handle<mirror::DexCache> dex_cache,
5520 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005521 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005522 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005523 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005524 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005525 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005526 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005527 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005528 // TODO: we used to throw here if resolved's class loader was not the
5529 // boot class loader. This was to permit different classes with the
5530 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005531 dex_cache->SetResolvedType(type_idx, resolved);
5532 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005533 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005534 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005535 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005536 StackHandleScope<1> hs(self);
5537 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005538 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005539 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005540 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005541 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005542 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005543 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005544 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005545 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005546 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005547 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005548 return resolved;
5549}
5550
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005551mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005552 Handle<mirror::DexCache> dex_cache,
5553 Handle<mirror::ClassLoader> class_loader,
5554 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005555 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005556 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005557 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005558 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005559 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005560 return resolved;
5561 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005562 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005563 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005564 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005565 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005566 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005567 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005568 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005569 // Scan using method_idx, this saves string compares but will only hit for matching dex
5570 // caches/files.
5571 switch (type) {
5572 case kDirect: // Fall-through.
5573 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005574 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005575 break;
5576 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005577 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005578 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005579 break;
5580 case kSuper: // Fall-through.
5581 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005582 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005583 break;
5584 default:
5585 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005586 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005587 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005588 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005589 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005590 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005591 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005592 switch (type) {
5593 case kDirect: // Fall-through.
5594 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005595 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005596 break;
5597 case kInterface:
5598 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005599 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005600 break;
5601 case kSuper: // Fall-through.
5602 case kVirtual:
5603 resolved = klass->FindVirtualMethod(name, signature);
5604 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005605 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005606 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005607 // If we found a method, check for incompatible class changes.
5608 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005609 // Be a good citizen and update the dex cache to speed subsequent calls.
5610 dex_cache->SetResolvedMethod(method_idx, resolved);
5611 return resolved;
5612 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005613 // If we had a method, it's an incompatible-class-change error.
5614 if (resolved != nullptr) {
5615 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5616 } else {
5617 // We failed to find the method which means either an access error, an incompatible class
5618 // change, or no such method. First try to find the method among direct and virtual methods.
5619 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5620 const Signature signature = dex_file.GetMethodSignature(method_id);
5621 switch (type) {
5622 case kDirect:
5623 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005624 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005625 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5626 // have had a resolved method before, which triggers the "true" branch above.
5627 break;
5628 case kInterface:
5629 case kVirtual:
5630 case kSuper:
5631 resolved = klass->FindDirectMethod(name, signature);
5632 break;
5633 }
5634
5635 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005636 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005637 if (resolved != nullptr && referrer.Get() != nullptr) {
5638 mirror::Class* methods_class = resolved->GetDeclaringClass();
5639 mirror::Class* referring_class = referrer->GetDeclaringClass();
5640 if (!referring_class->CanAccess(methods_class)) {
5641 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5642 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005643 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005644 } else if (!referring_class->CanAccessMember(methods_class,
5645 resolved->GetAccessFlags())) {
5646 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005647 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005648 }
5649 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005650 if (!exception_generated) {
5651 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5652 // interface methods and throw if we find the method there. If we find nothing, throw a
5653 // NoSuchMethodError.
5654 switch (type) {
5655 case kDirect:
5656 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005657 if (resolved != nullptr) {
5658 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5659 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005660 resolved = klass->FindInterfaceMethod(name, signature);
5661 if (resolved != nullptr) {
5662 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5663 } else {
5664 ThrowNoSuchMethodError(type, klass, name, signature);
5665 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005666 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005667 break;
5668 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005669 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005670 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5671 } else {
5672 resolved = klass->FindVirtualMethod(name, signature);
5673 if (resolved != nullptr) {
5674 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5675 } else {
5676 ThrowNoSuchMethodError(type, klass, name, signature);
5677 }
5678 }
5679 break;
5680 case kSuper:
5681 if (resolved != nullptr) {
5682 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005683 } else {
5684 ThrowNoSuchMethodError(type, klass, name, signature);
5685 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005686 break;
5687 case kVirtual:
5688 if (resolved != nullptr) {
5689 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5690 } else {
5691 resolved = klass->FindInterfaceMethod(name, signature);
5692 if (resolved != nullptr) {
5693 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5694 } else {
5695 ThrowNoSuchMethodError(type, klass, name, signature);
5696 }
5697 }
5698 break;
5699 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005700 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005701 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005702 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005703 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005704 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005705}
5706
Mathieu Chartier590fee92013-09-13 13:46:47 -07005707mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005708 Handle<mirror::DexCache> dex_cache,
5709 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005710 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005711 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005712 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005713 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005714 return resolved;
5715 }
5716 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005717 Thread* const self = Thread::Current();
5718 StackHandleScope<1> hs(self);
5719 Handle<mirror::Class> klass(
5720 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005721 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005722 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005723 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005724 }
5725
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005726 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005727 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005728 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005729 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005730 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005731
Andreas Gampe58a5af82014-07-31 16:23:49 -07005732 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005733 const char* name = dex_file.GetFieldName(field_id);
5734 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5735 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005736 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005737 } else {
5738 resolved = klass->FindInstanceField(name, type);
5739 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005740 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005741 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005742 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005743 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005744 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005745 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005746 return resolved;
5747}
5748
Brian Carlstromea46f952013-07-30 01:26:50 -07005749mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005750 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005751 Handle<mirror::DexCache> dex_cache,
5752 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005753 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005754 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005755 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005756 return resolved;
5757 }
5758 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005759 Thread* self = Thread::Current();
5760 StackHandleScope<1> hs(self);
5761 Handle<mirror::Class> klass(
5762 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005763 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005764 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005765 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005766 }
5767
Ian Rogersdfb325e2013-10-30 01:00:44 -07005768 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5769 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005770 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005771 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005772 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005773 dex_cache->SetResolvedField(field_idx, resolved);
5774 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005775 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005776 }
5777 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005778}
5779
Brian Carlstromea46f952013-07-30 01:26:50 -07005780const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005781 uint32_t* length) {
5782 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5783 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005784 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005785 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005786 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005787}
5788
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005789void ClassLinker::DumpAllClasses(int flags) {
5790 if (dex_cache_image_class_lookup_required_) {
5791 MoveImageClassesToClassTable();
5792 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005793 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5794 // 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 -08005795 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005796 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005797 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005798 for (GcRoot<mirror::Class>& it : class_table_) {
5799 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005800 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005801 }
5802
5803 for (size_t i = 0; i < all_classes.size(); ++i) {
5804 all_classes[i]->DumpClass(std::cerr, flags);
5805 }
5806}
5807
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005808static OatFile::OatMethod CreateOatMethod(const void* code, bool is_portable) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005809 CHECK_EQ(kUsePortableCompiler, is_portable);
5810 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005811 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5812 base -= sizeof(void*); // Move backward so that code_offset != 0.
5813 const uint32_t code_offset = sizeof(void*);
5814 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005815}
5816
5817bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5818 return (entry_point == GetPortableResolutionStub()) ||
5819 (portable_resolution_trampoline_ == entry_point);
5820}
5821
5822bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5823 return (entry_point == GetQuickResolutionStub()) ||
5824 (quick_resolution_trampoline_ == entry_point);
5825}
5826
5827bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5828 return (entry_point == GetPortableToInterpreterBridge());
5829 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5830}
5831
5832bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5833 return (entry_point == GetQuickToInterpreterBridge()) ||
5834 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5835}
5836
5837bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5838 return (entry_point == GetQuickGenericJniStub()) ||
5839 (quick_generic_jni_trampoline_ == entry_point);
5840}
5841
5842const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5843 return GetQuickGenericJniStub();
5844}
5845
5846void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5847 bool is_portable) const {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005848 OatFile::OatMethod oat_method = CreateOatMethod(method_code, is_portable);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005849 oat_method.LinkMethod(method);
5850 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5851 // Create bridges to transition between different kinds of compiled bridge.
5852 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5853 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5854 } else {
5855 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5856 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5857 method->SetIsPortableCompiled();
5858 }
5859}
5860
5861void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5862 if (!method->IsNative()) {
5863 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5864 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5865 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5866 } else {
5867 const void* quick_method_code = GetQuickGenericJniStub();
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005868 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, false);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005869 oat_method.LinkMethod(method);
5870 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5871 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5872 }
5873}
5874
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005875void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005876 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005877 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005878 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005879 MoveImageClassesToClassTable();
5880 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005881 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005882 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5883 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005884}
5885
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005886size_t ClassLinker::NumLoadedClasses() {
5887 if (dex_cache_image_class_lookup_required_) {
5888 MoveImageClassesToClassTable();
5889 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005890 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005891 // Only return non zygote classes since these are the ones which apps which care about.
5892 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005893}
5894
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005895pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005896 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005897}
5898
5899pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005900 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005901}
5902
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005903void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005904 DCHECK(!init_done_);
5905
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005906 DCHECK(klass != nullptr);
5907 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005908
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005909 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005910 DCHECK(class_roots != nullptr);
5911 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005912 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005913}
5914
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005915const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5916 static const char* class_roots_descriptors[] = {
5917 "Ljava/lang/Class;",
5918 "Ljava/lang/Object;",
5919 "[Ljava/lang/Class;",
5920 "[Ljava/lang/Object;",
5921 "Ljava/lang/String;",
5922 "Ljava/lang/DexCache;",
5923 "Ljava/lang/ref/Reference;",
5924 "Ljava/lang/reflect/ArtField;",
5925 "Ljava/lang/reflect/ArtMethod;",
5926 "Ljava/lang/reflect/Proxy;",
5927 "[Ljava/lang/String;",
5928 "[Ljava/lang/reflect/ArtField;",
5929 "[Ljava/lang/reflect/ArtMethod;",
5930 "Ljava/lang/ClassLoader;",
5931 "Ljava/lang/Throwable;",
5932 "Ljava/lang/ClassNotFoundException;",
5933 "Ljava/lang/StackTraceElement;",
5934 "Z",
5935 "B",
5936 "C",
5937 "D",
5938 "F",
5939 "I",
5940 "J",
5941 "S",
5942 "V",
5943 "[Z",
5944 "[B",
5945 "[C",
5946 "[D",
5947 "[F",
5948 "[I",
5949 "[J",
5950 "[S",
5951 "[Ljava/lang/StackTraceElement;",
5952 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005953 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5954 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005955
5956 const char* descriptor = class_roots_descriptors[class_root];
5957 CHECK(descriptor != nullptr);
5958 return descriptor;
5959}
5960
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005961std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5962 const {
5963 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005964 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005965}
5966
5967bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5968 const GcRoot<mirror::Class>& b) {
5969 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5970 return false;
5971 }
5972 std::string temp;
5973 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5974}
5975
5976std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5977 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005978 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005979}
5980
5981bool ClassLinker::ClassDescriptorHashEquals::operator()(
5982 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5983 if (a.Read()->GetClassLoader() != b.second) {
5984 return false;
5985 }
5986 return a.Read()->DescriptorEquals(b.first);
5987}
5988
5989bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5990 const char* descriptor) {
5991 return a.Read()->DescriptorEquals(descriptor);
5992}
5993
5994std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005995 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005996}
5997
Sebastien Hertz6963e442014-11-26 22:11:27 +01005998bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
5999 // Non-image methods don't use direct code pointer.
6000 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
6001 return false;
6002 }
6003 if (m->IsPrivate()) {
6004 // The method can only be called inside its own oat file. Therefore it won't be called using
6005 // its direct code if the oat file has been compiled in PIC mode.
6006 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
6007 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
6008 const OatFile::OatDexFile* oat_dex_file = class_linker->FindOpenedOatDexFileForDexFile(dex_file);
6009 if (oat_dex_file == nullptr) {
6010 // No oat file: the method has not been compiled.
6011 return false;
6012 }
6013 const OatFile* oat_file = oat_dex_file->GetOatFile();
6014 return oat_file != nullptr && !oat_file->IsPic();
6015 } else {
6016 // The method can be called outside its own oat file. Therefore it won't be called using its
6017 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
6018 ReaderMutexLock mu(Thread::Current(), dex_lock_);
6019 for (const OatFile* oat_file : oat_files_) {
6020 if (!oat_file->IsPic()) {
6021 return true;
6022 }
6023 }
6024 return false;
6025 }
6026}
6027
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006028} // namespace art