blob: 6aab632dd7d5dff59bbc9e73ab122bbabab3c79d [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
Ian Rogers98379392014-02-24 16:53:16 -0800578 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700579
Brian Carlstroma004aa92012-02-08 18:05:09 -0800580 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700581}
582
Ian Rogers98379392014-02-24 16:53:16 -0800583void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800584 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700585
586 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700587 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700588 // as the types of the field can't be resolved prior to the runtime being
589 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800590 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700591 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800592 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800593
Brian Carlstromea46f952013-07-30 01:26:50 -0700594 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700595 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
596 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700597
Brian Carlstromea46f952013-07-30 01:26:50 -0700598 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700599 CHECK_STREQ(queue->GetName(), "queue");
600 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700601
Brian Carlstromea46f952013-07-30 01:26:50 -0700602 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700603 CHECK_STREQ(queueNext->GetName(), "queueNext");
604 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700605
Brian Carlstromea46f952013-07-30 01:26:50 -0700606 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700607 CHECK_STREQ(referent->GetName(), "referent");
608 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700609
Brian Carlstromea46f952013-07-30 01:26:50 -0700610 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700611 CHECK_STREQ(zombie->GetName(), "zombie");
612 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700613
Brian Carlstroma663ea52011-08-19 23:33:41 -0700614 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700615 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700616 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800617 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700618 CHECK(klass != nullptr);
619 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700620 // note SetClassRoot does additional validation.
621 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700622 }
623
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700624 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700625
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700626 // disable the slow paths in FindClass and CreatePrimitiveClass now
627 // that Object, Class, and Object[] are setup
628 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700629
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800630 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700631}
632
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700633void ClassLinker::RunRootClinits() {
634 Thread* self = Thread::Current();
635 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800636 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700637 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700638 StackHandleScope<1> hs(self);
639 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700640 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700641 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700642 }
643 }
644}
645
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700646bool ClassLinker::GenerateOatFile(const char* dex_filename,
Brian Carlstromd601af82012-01-06 10:15:19 -0800647 int oat_fd,
Vladimir Marko60836d52014-01-16 15:53:38 +0000648 const char* oat_cache_filename,
649 std::string* error_msg) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700650 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700651 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800652
Ian Rogers1d54e732013-05-02 21:10:01 -0700653 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800654 std::string boot_image_option("--boot-image=");
Alex Light64ad14d2014-08-19 14:23:13 -0700655 if (heap->GetImageSpace() == nullptr) {
656 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
657 // out of space anyway it might not matter.
658 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
659 "without an image.", dex_filename);
660 return false;
661 }
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700662 boot_image_option += heap->GetImageSpace()->GetImageLocation();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800663
Brian Carlstrom6449c622014-02-10 23:48:36 -0800664 std::string dex_file_option("--dex-file=");
665 dex_file_option += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800666
Brian Carlstrom6449c622014-02-10 23:48:36 -0800667 std::string oat_fd_option("--oat-fd=");
668 StringAppendF(&oat_fd_option, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800669
Brian Carlstrom6449c622014-02-10 23:48:36 -0800670 std::string oat_location_option("--oat-location=");
671 oat_location_option += oat_cache_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800672
Brian Carlstrom6449c622014-02-10 23:48:36 -0800673 std::vector<std::string> argv;
674 argv.push_back(dex2oat);
675 argv.push_back("--runtime-arg");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800676 argv.push_back("-classpath");
677 argv.push_back("--runtime-arg");
Brian Carlstrom35d8b8e2014-02-25 10:51:11 -0800678 argv.push_back(Runtime::Current()->GetClassPathString());
Dave Allisonb373e092014-02-20 16:06:36 -0800679
Ian Rogers8afeb852014-04-02 14:55:49 -0700680 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Dave Allisonb373e092014-02-20 16:06:36 -0800681
Jeff Hao4a200f52014-04-01 14:58:49 -0700682 if (!Runtime::Current()->IsVerificationEnabled()) {
683 argv.push_back("--compiler-filter=verify-none");
684 }
685
Alex Light6e183f22014-07-18 14:57:04 -0700686 if (Runtime::Current()->MustRelocateIfPossible()) {
687 argv.push_back("--runtime-arg");
688 argv.push_back("-Xrelocate");
689 } else {
690 argv.push_back("--runtime-arg");
691 argv.push_back("-Xnorelocate");
692 }
693
Brian Carlstrom6449c622014-02-10 23:48:36 -0800694 if (!kIsTargetBuild) {
695 argv.push_back("--host");
buzbeea024a062013-07-31 10:47:37 -0700696 }
Ian Rogers8afeb852014-04-02 14:55:49 -0700697
Brian Carlstrom6449c622014-02-10 23:48:36 -0800698 argv.push_back(boot_image_option);
699 argv.push_back(dex_file_option);
700 argv.push_back(oat_fd_option);
701 argv.push_back(oat_location_option);
702 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800703 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800704 argv.push_back(compiler_options[i].c_str());
jeffhao262bf462011-10-20 18:36:32 -0700705 }
Brian Carlstrom6449c622014-02-10 23:48:36 -0800706
707 return Exec(argv, error_msg);
jeffhao262bf462011-10-20 18:36:32 -0700708}
709
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700710const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700711 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800712 if (kIsDebugBuild) {
713 for (size_t i = 0; i < oat_files_.size(); ++i) {
714 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700715 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800716 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700717 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
718 oat_files_.push_back(oat_file);
719 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800720}
721
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700722OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
723 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700724 OatFile* oat_file = space->ReleaseOatFile();
725 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700726 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700727 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700728}
729
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100730const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800731 const char* dex_location = dex_file.GetLocation().c_str();
732 uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100733 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
Brian Carlstrom5b332c82012-02-01 15:02:31 -0800734}
735
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100736const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
737 const char* dex_location,
738 const uint32_t* dex_location_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700739 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100740 for (const OatFile* oat_file : oat_files_) {
741 DCHECK(oat_file != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700742
743 if (oat_location != nullptr) {
744 if (oat_file->GetLocation() != oat_location) {
745 continue;
746 }
747 }
748
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700749 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
Brian Carlstrom08cbf662013-12-10 16:52:57 -0800750 dex_location_checksum,
Brian Carlstrom756ee4e2013-10-03 15:46:12 -0700751 false);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100752 if (oat_dex_file != nullptr) {
753 return oat_dex_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800754 }
755 }
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100756 return nullptr;
Brian Carlstromae826982011-11-09 01:33:42 -0800757}
758
Calin Juravle621962a2014-09-02 15:53:55 +0100759
760// Loads all multi dex files from the given oat file returning true on success.
761//
762// Parameters:
763// oat_file - the oat file to load from
764// dex_location - the dex location used to generate the oat file
765// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
766// generated - whether or not the oat_file existed before or was just (re)generated
767// error_msgs - any error messages will be appended here
768// dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
769static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
770 const char* dex_location,
771 const uint32_t* dex_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700772 bool generated,
773 std::vector<std::string>* error_msgs,
774 std::vector<const DexFile*>* dex_files) {
775 if (oat_file == nullptr) {
776 return false;
777 }
778
779 size_t old_size = dex_files->size(); // To rollback on error.
780
781 bool success = true;
782 for (size_t i = 0; success; ++i) {
Calin Juravle4e1d5792014-07-15 23:56:47 +0100783 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
Andreas Gampe833a4852014-05-21 18:46:59 -0700784 const char* next_name = next_name_str.c_str();
785
Calin Juravle621962a2014-09-02 15:53:55 +0100786 uint32_t next_location_checksum;
787 uint32_t* next_location_checksum_pointer = &next_location_checksum;
Andreas Gampe833a4852014-05-21 18:46:59 -0700788 std::string error_msg;
Calin Juravle621962a2014-09-02 15:53:55 +0100789 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
790 // When i=0 the multidex name should be the same as the location name. We already have the
791 // checksum it so we don't need to recompute it.
792 if (dex_location_checksum == nullptr) {
793 next_location_checksum_pointer = nullptr;
794 } else {
795 next_location_checksum = *dex_location_checksum;
796 }
797 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700798 DCHECK_EQ(false, i == 0 && generated);
Calin Juravle621962a2014-09-02 15:53:55 +0100799 next_location_checksum_pointer = nullptr;
Andreas Gampe833a4852014-05-21 18:46:59 -0700800 }
801
802 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
803
804 if (oat_dex_file == nullptr) {
805 if (i == 0 && generated) {
Andreas Gampe833a4852014-05-21 18:46:59 -0700806 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
Calin Juravle621962a2014-09-02 15:53:55 +0100807 " file'%s'", dex_location, next_location_checksum,
Andreas Gampe833a4852014-05-21 18:46:59 -0700808 oat_file->GetLocation().c_str());
809 error_msgs->push_back(error_msg);
810 }
811 break; // Not found, done.
812 }
813
814 // Checksum test. Test must succeed when generated.
815 success = !generated;
Calin Juravle621962a2014-09-02 15:53:55 +0100816 if (next_location_checksum_pointer != nullptr) {
817 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
Andreas Gampe833a4852014-05-21 18:46:59 -0700818 }
819
820 if (success) {
821 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
822 if (dex_file == nullptr) {
823 success = false;
824 error_msgs->push_back(error_msg);
825 } else {
826 dex_files->push_back(dex_file);
827 }
828 }
829
830 // When we generated the file, we expect success, or something is terribly wrong.
831 CHECK_EQ(false, generated && !success)
832 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
Calin Juravle621962a2014-09-02 15:53:55 +0100833 << std::hex << " dex_location_checksum=" << next_location_checksum
Andreas Gampe833a4852014-05-21 18:46:59 -0700834 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
835 }
836
837 if (dex_files->size() == old_size) {
838 success = false; // We did not even find classes.dex
839 }
840
841 if (success) {
842 return true;
843 } else {
844 // Free all the dex files we have loaded.
845 auto it = dex_files->begin() + old_size;
846 auto it_end = dex_files->end();
847 for (; it != it_end; it++) {
848 delete *it;
849 }
850 dex_files->erase(dex_files->begin() + old_size, it_end);
851
852 return false;
853 }
854}
855
856// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
857// complicates the loading process, as we should not use an iterative loading process, because that
858// would register the oat file and dex files that come before the broken one. Instead, check all
859// multidex ahead of time.
860bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
861 std::vector<std::string>* error_msgs,
862 std::vector<const DexFile*>* dex_files) {
863 // 1) Check whether we have an open oat file.
864 // This requires a dex checksum, use the "primary" one.
865 uint32_t dex_location_checksum;
866 uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
867 bool have_checksum = true;
868 std::string checksum_error_msg;
869 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
Calin Juravle621962a2014-09-02 15:53:55 +0100870 // This happens for pre-opted files since the corresponding dex files are no longer on disk.
Andreas Gampe833a4852014-05-21 18:46:59 -0700871 dex_location_checksum_pointer = nullptr;
872 have_checksum = false;
873 }
874
875 bool needs_registering = false;
876
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100877 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
878 dex_location_checksum_pointer);
879 std::unique_ptr<const OatFile> open_oat_file(
880 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -0700881
882 // 2) If we do not have an open one, maybe there's one on disk already.
883
884 // In case the oat file is not open, we play a locking game here so
885 // that if two different processes race to load and register or generate
886 // (or worse, one tries to open a partial generated file) we will be okay.
887 // This is actually common with apps that use DexClassLoader to work
888 // around the dex method reference limit and that have a background
889 // service running in a separate process.
890 ScopedFlock scoped_flock;
891
892 if (open_oat_file.get() == nullptr) {
893 if (oat_location != nullptr) {
894 // Can only do this if we have a checksum, else error.
895 if (!have_checksum) {
896 error_msgs->push_back(checksum_error_msg);
897 return false;
898 }
899
900 std::string error_msg;
901
902 // We are loading or creating one in the future. Time to set up the file lock.
903 if (!scoped_flock.Init(oat_location, &error_msg)) {
904 error_msgs->push_back(error_msg);
905 return false;
906 }
907
Alex Lighta59dd802014-07-02 16:28:08 -0700908 // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
Andreas Gampe833a4852014-05-21 18:46:59 -0700909 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
910 oat_location, &error_msg));
911
912 if (open_oat_file.get() == nullptr) {
913 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
914 dex_location, oat_location, error_msg.c_str());
915 VLOG(class_linker) << compound_msg;
916 error_msgs->push_back(compound_msg);
917 }
918 } else {
919 // TODO: What to lock here?
Calin Juravlec54aea72014-07-16 14:45:03 +0100920 bool obsolete_file_cleanup_failed;
Andreas Gampe833a4852014-05-21 18:46:59 -0700921 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
922 dex_location_checksum_pointer,
Calin Juravlec54aea72014-07-16 14:45:03 +0100923 kRuntimeISA, error_msgs,
924 &obsolete_file_cleanup_failed));
925 // There's no point in going forward and eventually try to regenerate the
926 // file if we couldn't remove the obsolete one. Mostly likely we will fail
927 // with the same error when trying to write the new file.
Calin Juravlec54aea72014-07-16 14:45:03 +0100928 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
929 if (obsolete_file_cleanup_failed) {
930 return false;
931 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700932 }
933 needs_registering = true;
934 }
935
936 // 3) If we have an oat file, check all contained multidex files for our dex_location.
937 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
Calin Juravle621962a2014-09-02 15:53:55 +0100938 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
939 dex_location_checksum_pointer,
940 false, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -0700941 if (success) {
942 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it.
943 if (needs_registering) {
944 // We opened the oat file, so we must register it.
945 RegisterOatFile(oat_file);
946 }
Alex Light9dcc4572014-08-14 14:16:26 -0700947 // If the file isn't executable we failed patchoat but did manage to get the dex files.
948 return oat_file->IsExecutable();
Andreas Gampe833a4852014-05-21 18:46:59 -0700949 } else {
950 if (needs_registering) {
951 // We opened it, delete it.
952 open_oat_file.reset();
953 } else {
954 open_oat_file.release(); // Do not delete open oat files.
955 }
956 }
957
958 // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
959
960 // Need a checksum, fail else.
961 if (!have_checksum) {
962 error_msgs->push_back(checksum_error_msg);
963 return false;
964 }
965
966 // Look in cache location if no oat_location is given.
967 std::string cache_location;
968 if (oat_location == nullptr) {
969 // Use the dalvik cache.
970 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
971 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
972 oat_location = cache_location.c_str();
973 }
974
Alex Light64ad14d2014-08-19 14:23:13 -0700975 bool has_flock = true;
Andreas Gampe833a4852014-05-21 18:46:59 -0700976 // Definitely need to lock now.
977 if (!scoped_flock.HasFile()) {
978 std::string error_msg;
979 if (!scoped_flock.Init(oat_location, &error_msg)) {
980 error_msgs->push_back(error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700981 has_flock = false;
Andreas Gampe833a4852014-05-21 18:46:59 -0700982 }
983 }
984
Alex Light64ad14d2014-08-19 14:23:13 -0700985 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +0100986 // Create the oat file.
987 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
988 oat_location, error_msgs));
989 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700990
991 // Failed, bail.
992 if (open_oat_file.get() == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +0100993 std::string error_msg;
994 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
995 DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
996 error_msgs->push_back(error_msg);
Andreas Gampe833a4852014-05-21 18:46:59 -0700997 return false;
998 }
999
1000 // Try to load again, but stronger checks.
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001001 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
1002 dex_location_checksum_pointer,
Calin Juravle621962a2014-09-02 15:53:55 +01001003 true, error_msgs, dex_files);
Andreas Gampe833a4852014-05-21 18:46:59 -07001004 if (success) {
1005 RegisterOatFile(open_oat_file.release());
1006 return true;
1007 } else {
1008 return false;
1009 }
1010}
1011
1012const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
1013 uint32_t dex_location_checksum,
1014 const char* oat_location,
1015 std::string* error_msg) {
Igor Murashkin46774762014-10-22 11:37:02 -07001016 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001017 !Runtime::Current()->IsCompiler(),
1018 error_msg));
1019 if (oat_file.get() == nullptr) {
1020 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
1021 error_msg->c_str());
1022 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001023 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001024 Runtime* runtime = Runtime::Current();
Alex Light7adb7ac2014-08-29 10:28:25 -07001025 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1026 if (image_space != nullptr) {
1027 const ImageHeader& image_header = image_space->GetImageHeader();
1028 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
1029 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
1030 if (expected_image_oat_checksum != actual_image_oat_checksum) {
1031 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
1032 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
1033 actual_image_oat_checksum);
1034 return nullptr;
1035 }
1036
1037 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1038 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
1039 if (expected_image_oat_offset != actual_image_oat_offset) {
1040 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
1041 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
1042 actual_image_oat_offset);
1043 return nullptr;
1044 }
1045 int32_t expected_patch_delta = image_header.GetPatchDelta();
1046 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1047 if (expected_patch_delta != actual_patch_delta) {
1048 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1049 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1050 return nullptr;
1051 }
Brian Carlstrom28db0122012-10-18 16:20:41 -07001052 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001053
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001054 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1055 &dex_location_checksum);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001056 if (oat_dex_file == nullptr) {
1057 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1058 dex_location);
1059 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001060 }
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001061 uint32_t expected_dex_checksum = dex_location_checksum;
1062 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1063 if (expected_dex_checksum != actual_dex_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001064 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1065 "found 0x%x", oat_location, expected_dex_checksum,
1066 actual_dex_checksum);
1067 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001068 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001069 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1070 if (dex_file.get() != nullptr) {
1071 return oat_file.release();
1072 } else {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001073 return nullptr;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001074 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001075}
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001076
Andreas Gampe833a4852014-05-21 18:46:59 -07001077const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1078 int fd, const char* oat_location,
1079 std::vector<std::string>* error_msgs) {
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001080 // Generate the output oat file for the dex file
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001081 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
Andreas Gampe833a4852014-05-21 18:46:59 -07001082 std::string error_msg;
1083 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
Andreas Gampe329d1882014-04-08 10:32:19 -07001084 CHECK(!error_msg.empty());
1085 error_msgs->push_back(error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001086 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001087 }
Igor Murashkin46774762014-10-22 11:37:02 -07001088 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr,
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001089 !Runtime::Current()->IsCompiler(),
1090 &error_msg));
1091 if (oat_file.get() == nullptr) {
Andreas Gampe833a4852014-05-21 18:46:59 -07001092 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1093 oat_location, error_msg.c_str());
Andreas Gampe329d1882014-04-08 10:32:19 -07001094 error_msgs->push_back(compound_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001095 return nullptr;
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001096 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001097
1098 return oat_file.release();
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001099}
1100
Alex Light6e183f22014-07-18 14:57:04 -07001101bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1102 const InstructionSet instruction_set) {
1103 Runtime* runtime = Runtime::Current();
1104 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001105 if (image_space == nullptr) {
1106 return false;
1107 }
Alex Light6e183f22014-07-18 14:57:04 -07001108 uint32_t image_oat_checksum = 0;
1109 if (instruction_set == kRuntimeISA) {
1110 const ImageHeader& image_header = image_space->GetImageHeader();
1111 image_oat_checksum = image_header.GetOatChecksum();
1112 } else {
1113 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1114 image_space->GetImageLocation().c_str(), instruction_set));
1115 image_oat_checksum = image_header->GetOatChecksum();
1116 }
1117 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1118}
1119
1120bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1121 const InstructionSet instruction_set,
1122 std::string* error_msg) {
Brian Carlstromafe25512012-06-27 17:02:58 -07001123 Runtime* runtime = Runtime::Current();
Narayan Kamath52f84882014-05-02 10:10:39 +01001124 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001125 if (image_space == nullptr) {
1126 *error_msg = "No image space for verification against";
1127 return false;
1128 }
Narayan Kamath52f84882014-05-02 10:10:39 +01001129
1130 // If the requested instruction set is the same as the current runtime,
1131 // we can use the checksums directly. If it isn't, we'll have to read the
1132 // image header from the image for the right instruction set.
1133 uint32_t image_oat_checksum = 0;
1134 uintptr_t image_oat_data_begin = 0;
Alex Lighta59dd802014-07-02 16:28:08 -07001135 int32_t image_patch_delta = 0;
Brian Carlstrom31d8f522014-09-29 11:22:54 -07001136 if (instruction_set == runtime->GetInstructionSet()) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001137 const ImageHeader& image_header = image_space->GetImageHeader();
1138 image_oat_checksum = image_header.GetOatChecksum();
1139 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001140 image_patch_delta = image_header.GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001141 } else {
Ian Rogers700a4022014-05-19 16:49:03 -07001142 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
Narayan Kamath52f84882014-05-02 10:10:39 +01001143 image_space->GetImageLocation().c_str(), instruction_set));
1144 image_oat_checksum = image_header->GetOatChecksum();
1145 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
Alex Lighta59dd802014-07-02 16:28:08 -07001146 image_patch_delta = image_header->GetPatchDelta();
Narayan Kamath52f84882014-05-02 10:10:39 +01001147 }
1148 const OatHeader& oat_header = oat_file->GetOatHeader();
Igor Murashkin96e83932014-10-29 19:45:42 -07001149 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum);
1150
1151 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks.
1152 if (!oat_file->IsPic()) {
1153 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta)
1154 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin);
1155 }
Alex Light6e183f22014-07-18 14:57:04 -07001156 if (!ret) {
1157 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1158 oat_file->GetLocation().c_str(),
1159 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1160 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1161 oat_file->GetOatHeader().GetImagePatchDelta(),
1162 image_oat_checksum, image_oat_data_begin, image_patch_delta);
1163 }
1164 return ret;
1165}
1166
1167bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1168 const char* dex_location,
1169 uint32_t dex_location_checksum,
1170 const InstructionSet instruction_set,
1171 std::string* error_msg) {
1172 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1173 return false;
1174 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001175
Brian Carlstromf3632832014-05-20 15:36:53 -07001176 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1177 &dex_location_checksum);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001178 if (oat_dex_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001179 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1180 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001181 for (const OatFile::OatDexFile* oat_dex_file_in : oat_file->GetOatDexFiles()) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001182 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001183 oat_file->GetLocation().c_str(),
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001184 oat_dex_file_in->GetDexFileLocation().c_str(),
1185 oat_dex_file_in->GetDexFileLocationChecksum());
Brian Carlstromafe25512012-06-27 17:02:58 -07001186 }
1187 return false;
1188 }
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001189
Calin Juravlea8c55ae2014-09-05 16:14:19 +01001190 DCHECK_EQ(dex_location_checksum, oat_dex_file->GetDexFileLocationChecksum());
Alex Light6e183f22014-07-18 14:57:04 -07001191 return true;
Brian Carlstromafe25512012-06-27 17:02:58 -07001192}
1193
Alex Lighta59dd802014-07-02 16:28:08 -07001194bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1195 const char* dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001196 const uint32_t* dex_location_checksum,
Alex Lighta59dd802014-07-02 16:28:08 -07001197 std::string* error_msg) {
1198 CHECK(oat_file != nullptr);
1199 CHECK(dex_location != nullptr);
Andreas Gampe833a4852014-05-21 18:46:59 -07001200 std::unique_ptr<const DexFile> dex_file;
Calin Juravle621962a2014-09-02 15:53:55 +01001201 if (dex_location_checksum == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001202 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1203 // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1204 // directory.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001205 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001206 if (oat_dex_file == nullptr) {
1207 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
Alex Lighta59dd802014-07-02 16:28:08 -07001208 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001209 error_msg->c_str());
Alex Lighta59dd802014-07-02 16:28:08 -07001210 return false;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001211 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001212 dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001213 } else {
Calin Juravle621962a2014-09-02 15:53:55 +01001214 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
Alex Light6e183f22014-07-18 14:57:04 -07001215 kRuntimeISA, error_msg);
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001216 if (!verified) {
Alex Lighta59dd802014-07-02 16:28:08 -07001217 return false;
Vladimir Marko64e7ac02014-05-01 15:43:47 +01001218 }
Andreas Gampe833a4852014-05-21 18:46:59 -07001219 dex_file.reset(oat_file->GetOatDexFile(dex_location,
Calin Juravle621962a2014-09-02 15:53:55 +01001220 dex_location_checksum)->OpenDexFile(error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001221 }
Alex Lighta59dd802014-07-02 16:28:08 -07001222 return dex_file.get() != nullptr;
Brian Carlstrom46b8a622012-06-19 23:13:22 -07001223}
1224
Andreas Gampe833a4852014-05-21 18:46:59 -07001225const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
Brian Carlstromf3632832014-05-20 15:36:53 -07001226 const char* dex_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001227 const uint32_t* dex_location_checksum,
Brian Carlstromf3632832014-05-20 15:36:53 -07001228 InstructionSet isa,
Calin Juravlec54aea72014-07-16 14:45:03 +01001229 std::vector<std::string>* error_msgs,
1230 bool* obsolete_file_cleanup_failed) {
1231 *obsolete_file_cleanup_failed = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001232 bool already_opened = false;
1233 std::string dex_location_str(dex_location);
1234 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1235 &already_opened,
1236 obsolete_file_cleanup_failed,
1237 error_msgs));
Andreas Gampe329d1882014-04-08 10:32:19 -07001238 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001239 if (oat_file.get() == nullptr) {
1240 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1241 dex_location));
1242 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001243 } else if (oat_file->IsExecutable() &&
Calin Juravle621962a2014-09-02 15:53:55 +01001244 !VerifyOatWithDexFile(oat_file.get(), dex_location,
1245 dex_location_checksum, &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001246 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1247 "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
Andreas Gampe329d1882014-04-08 10:32:19 -07001248 error_msg.c_str()));
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001249 return nullptr;
Alex Light9dcc4572014-08-14 14:16:26 -07001250 } else if (!oat_file->IsExecutable() &&
Alex Light84d76052014-08-22 17:49:35 -07001251 Runtime::Current()->GetHeap()->HasImageSpace() &&
Alex Light9dcc4572014-08-14 14:16:26 -07001252 !VerifyOatImageChecksum(oat_file.get(), isa)) {
1253 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1254 "dex location '%s'. Image checksum incorrect.",
1255 oat_file->GetLocation().c_str(), dex_location));
1256 return nullptr;
Alex Lighta59dd802014-07-02 16:28:08 -07001257 } else {
1258 return oat_file.release();
Brian Carlstrom08cbf662013-12-10 16:52:57 -08001259 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001260}
1261
Brian Carlstromae826982011-11-09 01:33:42 -08001262const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001263 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001264 for (size_t i = 0; i < oat_files_.size(); i++) {
1265 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001266 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -08001267 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001268 return oat_file;
1269 }
1270 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001271 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -07001272}
Brian Carlstromaded5f72011-10-07 17:15:04 -07001273
Alex Lighta59dd802014-07-02 16:28:08 -07001274const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1275 InstructionSet isa,
1276 bool *already_opened,
1277 bool *obsolete_file_cleanup_failed,
1278 std::vector<std::string>* error_msgs) {
1279 // Find out if we've already opened the file
1280 const OatFile* ret = nullptr;
1281 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1282 ret = FindOpenedOatFileFromOatLocation(odex_filename);
1283 if (ret != nullptr) {
1284 *already_opened = true;
1285 return ret;
1286 }
1287
1288 std::string dalvik_cache;
1289 bool have_android_data = false;
1290 bool have_dalvik_cache = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001291 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001292 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001293 &have_android_data, &have_dalvik_cache, &is_global_cache);
Alex Lighta59dd802014-07-02 16:28:08 -07001294 std::string cache_filename;
1295 if (have_dalvik_cache) {
1296 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1297 ret = FindOpenedOatFileFromOatLocation(cache_filename);
1298 if (ret != nullptr) {
1299 *already_opened = true;
1300 return ret;
1301 }
1302 } else {
1303 // If we need to relocate we should just place odex back where it started.
1304 cache_filename = odex_filename;
1305 }
1306
1307 ret = nullptr;
1308
1309 // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1310 //
1311 // Now we do the following:
1312 // 1) Try and open the odex version
1313 // 2) If present, checksum-verified & relocated correctly return it
1314 // 3) Close the odex version to free up its address space.
1315 // 4) Try and open the cache version
1316 // 5) If present, checksum-verified & relocated correctly return it
1317 // 6) Close the cache version to free up its address space.
1318 // 7) If we should relocate:
1319 // a) If we have opened and checksum-verified the odex version relocate it to
1320 // 'cache_filename' and return it
1321 // b) If we have opened and checksum-verified the cache version relocate it in place and return
1322 // it. This should not happen often (I think only the run-test's will hit this case).
1323 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1324 // this point.
1325 // 9) Return nullptr
1326
1327 *already_opened = false;
1328 const Runtime* runtime = Runtime::Current();
1329 CHECK(runtime != nullptr);
1330 bool executable = !runtime->IsCompiler();
1331
1332 std::string odex_error_msg;
1333 bool should_patch_system = false;
1334 bool odex_checksum_verified = false;
Alex Light84d76052014-08-22 17:49:35 -07001335 bool have_system_odex = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001336 {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001337 // There is a high probability that both these oat files map similar/the same address
Alex Lighta59dd802014-07-02 16:28:08 -07001338 // spaces so we must scope them like this so they each gets its turn.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001339 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001340 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001341 executable, &odex_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001342 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001343 &odex_checksum_verified,
1344 &odex_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001345 return odex_oat_file.release();
Alex Light84d76052014-08-22 17:49:35 -07001346 } else {
1347 if (odex_checksum_verified) {
1348 // We can just relocate
1349 should_patch_system = true;
1350 odex_error_msg = "Image Patches are incorrect";
1351 }
1352 if (odex_oat_file.get() != nullptr) {
1353 have_system_odex = true;
1354 }
Alex Lighta59dd802014-07-02 16:28:08 -07001355 }
1356 }
1357
Alex Lighta59dd802014-07-02 16:28:08 -07001358 std::string cache_error_msg;
1359 bool should_patch_cache = false;
1360 bool cache_checksum_verified = false;
1361 if (have_dalvik_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001362 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
Igor Murashkin46774762014-10-22 11:37:02 -07001363 nullptr,
Alex Lighta59dd802014-07-02 16:28:08 -07001364 executable, &cache_error_msg));
Andreas Gampe7ba64962014-10-23 11:37:40 -07001365 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001366 &cache_checksum_verified,
1367 &cache_error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001368 return cache_oat_file.release();
1369 } else if (cache_checksum_verified) {
1370 // We can just relocate
1371 should_patch_cache = true;
1372 cache_error_msg = "Image Patches are incorrect";
1373 }
1374 } else if (have_android_data) {
1375 // dalvik_cache does not exist but android data does. This means we should be able to create
1376 // it, so we should try.
1377 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1378 }
1379
1380 ret = nullptr;
1381 std::string error_msg;
1382 if (runtime->CanRelocate()) {
1383 // Run relocation
Alex Light64ad14d2014-08-19 14:23:13 -07001384 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1385 if (space != nullptr) {
1386 const std::string& image_location = space->GetImageLocation();
1387 if (odex_checksum_verified && should_patch_system) {
1388 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1389 } else if (cache_checksum_verified && should_patch_cache) {
1390 CHECK(have_dalvik_cache);
1391 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1392 }
Alex Light84d76052014-08-22 17:49:35 -07001393 } else if (have_system_odex) {
1394 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001395 }
1396 }
1397 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1398 // implicitly: were able to fine where the cached version is but we were unable to use it,
1399 // either as a destination for relocation or to open a file. We should delete it if it is
1400 // there.
1401 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1402 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1403 "searching for dex file %s: %s",
1404 cache_filename.c_str(), dex_location.c_str(),
1405 strerror(errno));
1406 error_msgs->push_back(rm_error_msg);
1407 VLOG(class_linker) << rm_error_msg;
1408 // Let the caller know that we couldn't remove the obsolete file.
1409 // This is a good indication that further writes may fail as well.
1410 *obsolete_file_cleanup_failed = true;
1411 }
1412 }
1413 if (ret == nullptr) {
1414 VLOG(class_linker) << error_msg;
1415 error_msgs->push_back(error_msg);
1416 std::string relocation_msg;
1417 if (runtime->CanRelocate()) {
1418 relocation_msg = StringPrintf(" and relocation failed");
1419 }
1420 if (have_dalvik_cache && cache_checksum_verified) {
1421 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1422 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1423 cache_filename.c_str(), cache_error_msg.c_str(),
1424 relocation_msg.c_str());
1425 } else {
1426 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1427 "dalvik_cache availible)%s.", odex_filename.c_str(),
1428 odex_error_msg.c_str(), relocation_msg.c_str());
1429 }
1430 VLOG(class_linker) << error_msg;
1431 error_msgs->push_back(error_msg);
1432 }
1433 return ret;
1434}
1435
Alex Light9dcc4572014-08-14 14:16:26 -07001436const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1437 InstructionSet isa,
1438 std::string* error_msg) {
1439 // We open it non-executable
Igor Murashkin46774762014-10-22 11:37:02 -07001440 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg));
Alex Light9dcc4572014-08-14 14:16:26 -07001441 if (output.get() == nullptr) {
1442 return nullptr;
1443 }
Alex Light84d76052014-08-22 17:49:35 -07001444 if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1445 VerifyOatImageChecksum(output.get(), isa)) {
Alex Light9dcc4572014-08-14 14:16:26 -07001446 return output.release();
1447 } else {
1448 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1449 oat_path.c_str());
1450 return nullptr;
1451 }
1452}
1453
Alex Lighta59dd802014-07-02 16:28:08 -07001454const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1455 const std::string& output_oat,
1456 const std::string& image_location,
1457 InstructionSet isa,
1458 std::string* error_msg) {
Andreas Gampe7ba64962014-10-23 11:37:40 -07001459 Runtime* runtime = Runtime::Current();
1460 DCHECK(runtime != nullptr);
1461 if (!runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07001462 // We don't have an image space so there is no point in trying to patchoat.
1463 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1464 << "running without an image. Attempting to use oat file for interpretation.";
1465 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1466 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001467 if (!runtime->IsDex2OatEnabled()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001468 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1469 // input_oat but make sure we only do interpretation on it's dex files.
1470 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1471 << "disabled. Attempting to use oat file for interpretation";
1472 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1473 }
Alex Lighta59dd802014-07-02 16:28:08 -07001474 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC.
Andreas Gampe7ba64962014-10-23 11:37:40 -07001475 std::string patchoat(runtime->GetPatchoatExecutable());
Alex Lighta59dd802014-07-02 16:28:08 -07001476
1477 std::string isa_arg("--instruction-set=");
1478 isa_arg += GetInstructionSetString(isa);
1479 std::string input_oat_filename_arg("--input-oat-file=");
1480 input_oat_filename_arg += input_oat;
1481 std::string output_oat_filename_arg("--output-oat-file=");
1482 output_oat_filename_arg += output_oat;
1483 std::string patched_image_arg("--patched-image-location=");
1484 patched_image_arg += image_location;
1485
1486 std::vector<std::string> argv;
1487 argv.push_back(patchoat);
1488 argv.push_back(isa_arg);
1489 argv.push_back(input_oat_filename_arg);
1490 argv.push_back(output_oat_filename_arg);
1491 argv.push_back(patched_image_arg);
1492
1493 std::string command_line(Join(argv, ' '));
1494 LOG(INFO) << "Relocate Oat File: " << command_line;
1495 bool success = Exec(argv, error_msg);
1496 if (success) {
Igor Murashkin46774762014-10-22 11:37:02 -07001497 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr,
Andreas Gampe7ba64962014-10-23 11:37:40 -07001498 !runtime->IsCompiler(), error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001499 bool checksum_verified = false;
Andreas Gampe7ba64962014-10-23 11:37:40 -07001500 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified,
1501 error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001502 return output.release();
1503 } else if (output.get() != nullptr) {
1504 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1505 "but output file '%s' failed verifcation: %s",
1506 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1507 } else {
1508 *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1509 "but was unable to open output file '%s': %s",
1510 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1511 }
Andreas Gampe7ba64962014-10-23 11:37:40 -07001512 } else if (!runtime->IsCompiler()) {
Alex Light9dcc4572014-08-14 14:16:26 -07001513 // patchoat failed which means we probably don't have enough room to place the output oat file,
1514 // instead of failing we should just run the interpreter from the dex files in the input oat.
1515 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1516 << "for interpretation. patchoat failure was: " << *error_msg;
1517 return GetInterpretedOnlyOat(input_oat, isa, error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -07001518 } else {
1519 *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1520 "failed: %s", input_oat.c_str(), output_oat.c_str(),
1521 error_msg->c_str());
1522 }
1523 return nullptr;
1524}
1525
Andreas Gampe7ba64962014-10-23 11:37:40 -07001526bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa,
Alex Lighta59dd802014-07-02 16:28:08 -07001527 bool* checksum_verified,
1528 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -07001529 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
Alex Light64ad14d2014-08-19 14:23:13 -07001530 if (image_space == nullptr) {
1531 *error_msg = "No image space present";
1532 return false;
1533 }
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001534 uint32_t real_image_checksum;
1535 void* real_image_oat_offset;
1536 int32_t real_patch_delta;
1537 if (isa == runtime->GetInstructionSet()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001538 const ImageHeader& image_header = image_space->GetImageHeader();
1539 real_image_checksum = image_header.GetOatChecksum();
1540 real_image_oat_offset = image_header.GetOatDataBegin();
1541 real_patch_delta = image_header.GetPatchDelta();
1542 } else {
1543 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1544 image_space->GetImageLocation().c_str(), isa));
1545 real_image_checksum = image_header->GetOatChecksum();
1546 real_image_oat_offset = image_header->GetOatDataBegin();
1547 real_patch_delta = image_header->GetPatchDelta();
1548 }
1549
1550 const OatHeader& oat_header = oat_file->GetOatHeader();
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001551 std::string compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001552
1553 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1554 *checksum_verified = oat_image_checksum == real_image_checksum;
1555 if (!*checksum_verified) {
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001556 StringAppendF(&compound_msg, " Oat Image Checksum Incorrect (expected 0x%x, received 0x%x)",
1557 real_image_checksum, oat_image_checksum);
Alex Lighta59dd802014-07-02 16:28:08 -07001558 }
1559
Andreas Gampe7ba64962014-10-23 11:37:40 -07001560 bool offset_verified;
1561 bool patch_delta_verified;
Alex Lighta59dd802014-07-02 16:28:08 -07001562
Andreas Gampe7ba64962014-10-23 11:37:40 -07001563 if (!oat_file->IsPic()) {
1564 // If an oat file is not PIC, we need to check that the image is at the expected location and
1565 // patched in the same way.
1566 void* oat_image_oat_offset =
1567 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1568 offset_verified = oat_image_oat_offset == real_image_oat_offset;
1569 if (!offset_verified) {
1570 StringAppendF(&compound_msg, " Oat Image oat offset incorrect (expected 0x%p, received 0x%p)",
1571 real_image_oat_offset, oat_image_oat_offset);
1572 }
1573
1574 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1575 patch_delta_verified = oat_patch_delta == real_patch_delta;
1576 if (!patch_delta_verified) {
1577 StringAppendF(&compound_msg, " Oat image patch delta incorrect (expected 0x%x, "
1578 "received 0x%x)", real_patch_delta, oat_patch_delta);
1579 }
1580 } else {
1581 // If an oat file is PIC, we ignore offset and patching delta.
1582 offset_verified = true;
1583 patch_delta_verified = true;
Alex Lighta59dd802014-07-02 16:28:08 -07001584 }
1585
1586 bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
Vladimir Marko30c2e1b2014-09-08 09:55:29 +01001587 if (!ret) {
1588 *error_msg = "Oat file failed to verify:" + compound_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001589 }
1590 return ret;
1591}
1592
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001593const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1594 std::string* error_msg) {
jeffhaof6174e82012-01-31 16:14:17 -08001595 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001596 if (oat_file != nullptr) {
jeffhaof6174e82012-01-31 16:14:17 -08001597 return oat_file;
1598 }
1599
Igor Murashkin46774762014-10-22 11:37:02 -07001600 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(),
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001601 error_msg);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001602}
1603
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001604static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
Ian Rogers848871b2013-08-05 10:56:33 -07001605 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001606 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1607
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001608 DCHECK(obj != nullptr);
1609 DCHECK(class_linker != nullptr);
Ian Rogers848871b2013-08-05 10:56:33 -07001610
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001611 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07001612 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -07001613 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07001614 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers848871b2013-08-05 10:56:33 -07001615 if (method != Runtime::Current()->GetResolutionMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001616 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1617 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Ian Rogers848871b2013-08-05 10:56:33 -07001618 }
1619 }
1620 }
1621}
1622
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001623void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001624 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001625 CHECK(!init_done_);
1626
Mathieu Chartier590fee92013-09-13 13:46:47 -07001627 Thread* self = Thread::Current();
Ian Rogers1d54e732013-05-02 21:10:01 -07001628 gc::Heap* heap = Runtime::Current()->GetHeap();
1629 gc::space::ImageSpace* space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001630 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001631 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001632 OatFile& oat_file = GetImageOatFile(space);
1633 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1634 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001635 const char* image_file_location = oat_file.GetOatHeader().
1636 GetStoreValueByKey(OatHeader::kImageLocationKey);
1637 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001638 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1639 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001640 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1641 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001642 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001643 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001644 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1645 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1646 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001647
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001648 StackHandleScope<1> hs(self);
1649 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1650 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1651 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001652 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001653
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001654 // Special case of setting up the String class early so that we can test arbitrary objects
1655 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001656 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001657
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001658 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001659 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001660 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001661 StackHandleScope<1> hs2(self);
1662 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001663 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001664 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1665 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001666 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001667 std::string error_msg;
1668 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001669 if (dex_file == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001670 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001671 << " from within oat file " << oat_file.GetLocation()
1672 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001673 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001674 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001675
1676 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1677
1678 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001679 }
1680
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001681 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1682 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001683 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001684 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
1685 if (!Runtime::Current()->IsCompiler()) {
1686 // Compiler supports having an image with a different pointer size than the runtime. This
1687 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1688 // also use 32 bit dex2oat on a system with 64 bit apps.
1689 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1690 << sizeof(void*);
1691 }
1692 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1693 image_pointer_size_ = 4;
1694 } else {
1695 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1696 image_pointer_size_ = 8;
1697 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001698
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001699 // Set entry point to interpreter if in InterpretOnly mode.
1700 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001701 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001702 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001703 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001704
1705 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001706 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001707 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001708
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001709 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001710 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001711 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001712 // String class root was set above
Fred Shih4ee7a662014-07-11 09:59:27 -07001713 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Brian Carlstromea46f952013-07-30 01:26:50 -07001714 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001715 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1716 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1717 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1718 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1719 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1720 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1721 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1722 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1723 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1724 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001725
Ian Rogers98379392014-02-24 16:53:16 -08001726 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001727
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001728 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001729}
1730
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001731void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1732 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1733 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001734 for (GcRoot<mirror::Class>& root : class_table_) {
1735 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1736 }
1737 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1738 root.VisitRoot(callback, arg, 0, kRootStickyClass);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001739 }
1740 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001741 for (auto& root : new_class_roots_) {
1742 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
1743 root.VisitRoot(callback, arg, 0, kRootStickyClass);
1744 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001745 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001746 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1747 // corresponding object. This is slow, but luckily for us, this may only happen with a
1748 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001749 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
1750 class_table_.Erase(it);
1751 class_table_.Insert(GcRoot<mirror::Class>(new_ref));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001752 }
1753 }
1754 }
1755 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1756 new_class_roots_.clear();
1757 }
1758 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1759 log_new_class_table_roots_ = true;
1760 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1761 log_new_class_table_roots_ = false;
1762 }
1763 // We deliberately ignore the class roots in the image since we
1764 // handle image roots by using the MS/CMS rescanning of dirty cards.
1765}
1766
Brian Carlstroma663ea52011-08-19 23:33:41 -07001767// Keep in sync with InitCallback. Anything we visit, we need to
1768// reinit references to when reinitializing a ClassLinker from a
1769// mapped image.
Mathieu Chartier893263b2014-03-04 11:07:42 -08001770void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001771 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers50b35e22012-10-04 10:09:15 -07001772 Thread* self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001773 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001774 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001775 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001776 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1777 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001778 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001779 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1780 for (size_t index : new_dex_cache_roots_) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001781 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
Mathieu Chartierc4621982013-09-16 19:43:47 -07001782 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001783 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001784 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1785 new_dex_cache_roots_.clear();
1786 }
1787 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1788 log_new_dex_caches_roots_ = true;
1789 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1790 log_new_dex_caches_roots_ = false;
1791 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001792 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001793 VisitClassRoots(callback, arg, flags);
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001794 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1795 DCHECK(!array_iftable_.IsNull());
Ian Rogers98379392014-02-24 16:53:16 -08001796 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001797 if (!find_array_class_cache_[i].IsNull()) {
1798 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
Ian Rogers98379392014-02-24 16:53:16 -08001799 }
1800 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001801}
1802
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001803void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1804 if (dex_cache_image_class_lookup_required_) {
1805 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001806 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001807 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001808 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001809 for (GcRoot<mirror::Class>& root : class_table_) {
1810 if (!visitor(root.Read(), arg)) {
1811 return;
1812 }
1813 }
1814 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1815 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001816 return;
1817 }
1818 }
1819}
1820
Ian Rogersdbf3be02014-08-29 15:40:08 -07001821static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001822 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001823 classes->insert(c);
1824 return true;
1825}
1826
Ian Rogersdbf3be02014-08-29 15:40:08 -07001827struct GetClassesVisitorArrayArg {
1828 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1829 int32_t index;
1830 bool success;
1831};
1832
1833static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1834 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1835 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1836 if (arg->index < (*arg->classes)->GetLength()) {
1837 (*arg->classes)->Set(arg->index, c);
1838 arg->index++;
1839 return true;
1840 } else {
1841 arg->success = false;
1842 return false;
1843 }
1844}
1845
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001846void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001847 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1848 // is avoiding duplicates.
1849 if (!kMovingClasses) {
1850 std::set<mirror::Class*> classes;
1851 VisitClasses(GetClassesVisitorSet, &classes);
1852 for (mirror::Class* klass : classes) {
1853 if (!visitor(klass, arg)) {
1854 return;
1855 }
1856 }
1857 } else {
1858 Thread* self = Thread::Current();
1859 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001860 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001861 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1862 GetClassesVisitorArrayArg local_arg;
1863 local_arg.classes = &classes;
1864 local_arg.success = false;
1865 // We size the array assuming classes won't be added to the class table during the visit.
1866 // If this assumption fails we iterate again.
1867 while (!local_arg.success) {
1868 size_t class_table_size;
1869 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001870 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001871 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001872 }
1873 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1874 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1875 classes.Assign(
1876 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1877 CHECK(classes.Get() != nullptr); // OOME.
1878 local_arg.index = 0;
1879 local_arg.success = true;
1880 VisitClasses(GetClassesVisitorArray, &local_arg);
1881 }
1882 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1883 // If the class table shrank during creation of the clases array we expect null elements. If
1884 // the class table grew then the loop repeats. If classes are created after the loop has
1885 // finished then we don't visit.
1886 mirror::Class* klass = classes->Get(i);
1887 if (klass != nullptr && !visitor(klass, arg)) {
1888 return;
1889 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001890 }
1891 }
1892}
1893
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001894ClassLinker::~ClassLinker() {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001895 mirror::Class::ResetClass();
1896 mirror::String::ResetClass();
Fred Shih4ee7a662014-07-11 09:59:27 -07001897 mirror::Reference::ResetClass();
Brian Carlstromea46f952013-07-30 01:26:50 -07001898 mirror::ArtField::ResetClass();
1899 mirror::ArtMethod::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001900 mirror::BooleanArray::ResetArrayClass();
1901 mirror::ByteArray::ResetArrayClass();
1902 mirror::CharArray::ResetArrayClass();
1903 mirror::DoubleArray::ResetArrayClass();
1904 mirror::FloatArray::ResetArrayClass();
1905 mirror::IntArray::ResetArrayClass();
1906 mirror::LongArray::ResetArrayClass();
1907 mirror::ShortArray::ResetArrayClass();
1908 mirror::Throwable::ResetClass();
1909 mirror::StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001910 STLDeleteElements(&boot_class_path_);
1911 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001912}
1913
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001914mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Ian Rogers1d54e732013-05-02 21:10:01 -07001915 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001916 StackHandleScope<16> hs(self);
1917 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1918 Handle<mirror::DexCache> dex_cache(
1919 hs.NewHandle(down_cast<mirror::DexCache*>(
1920 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1921 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001922 if (dex_cache.Get() == nullptr) {
1923 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001924 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001925 Handle<mirror::String>
1926 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001927 if (location.Get() == nullptr) {
1928 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001929 }
Ian Rogers700a4022014-05-19 16:49:03 -07001930 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001931 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001932 if (strings.Get() == nullptr) {
1933 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001934 }
Ian Rogers700a4022014-05-19 16:49:03 -07001935 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001936 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001937 if (types.Get() == nullptr) {
1938 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001939 }
Ian Rogers700a4022014-05-19 16:49:03 -07001940 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001941 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001942 if (methods.Get() == nullptr) {
1943 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001944 }
Ian Rogers700a4022014-05-19 16:49:03 -07001945 Handle<mirror::ObjectArray<mirror::ArtField>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001946 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001947 if (fields.Get() == nullptr) {
1948 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001949 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001950 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1951 fields.Get());
1952 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001953}
1954
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001955mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001956 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001957 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001958 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001959 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001960 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001961 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1962 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001963 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001964 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001965 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001966 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001967 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001968}
1969
Ian Rogers6fac4472014-02-25 17:01:10 -08001970mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001971 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001972}
1973
Brian Carlstromea46f952013-07-30 01:26:50 -07001974mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001975 return down_cast<mirror::ArtField*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001976 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
Brian Carlstroma0808032011-07-18 00:39:23 -07001977}
1978
Brian Carlstromea46f952013-07-30 01:26:50 -07001979mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001980 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001981 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001982}
1983
Mathieu Chartier590fee92013-09-13 13:46:47 -07001984mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1985 Thread* self, size_t length) {
1986 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1987 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001988}
1989
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001990mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1991 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001992 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001993
1994 // For temporary classes we must wait for them to be retired.
1995 if (init_done_ && klass->IsTemp()) {
1996 CHECK(!klass->IsResolved());
1997 if (klass->IsErroneous()) {
1998 ThrowEarlierClassFailure(klass);
1999 return nullptr;
2000 }
2001 StackHandleScope<1> hs(self);
2002 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2003 ObjectLock<mirror::Class> lock(self, h_class);
2004 // Loop and wait for the resolving thread to retire this class.
2005 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2006 lock.WaitIgnoringInterrupts();
2007 }
2008 if (h_class->IsErroneous()) {
2009 ThrowEarlierClassFailure(h_class.Get());
2010 return nullptr;
2011 }
2012 CHECK(h_class->IsRetired());
2013 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002014 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2015 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002016 }
2017
Brian Carlstromaded5f72011-10-07 17:15:04 -07002018 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002019 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002020 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002021 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2022 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002023 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002024 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2025 ThrowClassCircularityError(h_class.Get());
2026 h_class->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002027 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002028 }
2029 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002030 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08002031 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002032 }
2033 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002034
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002035 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002036 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002037 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002038 }
2039 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07002040 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08002041 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002042 return klass;
2043}
2044
Ian Rogers68b56852014-08-29 20:19:11 -07002045typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2046
2047// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002048ClassPathEntry FindInClassPath(const char* descriptor,
2049 size_t hash, const std::vector<const DexFile*>& class_path) {
2050 for (const DexFile* dex_file : class_path) {
2051 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002052 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002053 return ClassPathEntry(dex_file, dex_class_def);
2054 }
2055 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002056 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002057}
2058
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002059mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2060 Thread* self, const char* descriptor,
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002061 size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002062 Handle<mirror::ClassLoader> class_loader) {
Ian Rogers32427292014-11-19 14:05:21 -08002063 // Can we special case for a well understood PathClassLoader with the BootClassLoader as parent?
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002064 if (class_loader->GetClass() !=
2065 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2066 class_loader->GetParent()->GetClass() !=
2067 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2068 return nullptr;
2069 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002070 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002071 // Check if this would be found in the parent boot class loader.
2072 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002073 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002074 if (klass != nullptr) {
Ian Rogers32427292014-11-19 14:05:21 -08002075 // May return null if resolution on another thread fails.
2076 klass = EnsureResolved(self, descriptor, klass);
2077 } else {
2078 // May OOME.
2079 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2080 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002081 }
Ian Rogers32427292014-11-19 14:05:21 -08002082 if (klass == nullptr) {
2083 CHECK(self->IsExceptionPending()) << descriptor;
2084 self->ClearException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002085 }
Ian Rogers32427292014-11-19 14:05:21 -08002086 return klass;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002087 } else {
Ian Rogers32427292014-11-19 14:05:21 -08002088 // Handle as if this is the child PathClassLoader.
2089 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002090 StackHandleScope<3> hs(self);
2091 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2092 // We need to get the DexPathList and loop through it.
2093 Handle<mirror::ArtField> cookie_field =
2094 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2095 Handle<mirror::ArtField> dex_file_field =
2096 hs.NewHandle(
Andreas Gampec8ccf682014-09-29 20:07:43 -07002097 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002098 mirror::Object* dex_path_list =
2099 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2100 GetObject(class_loader.Get());
2101 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2102 cookie_field.Get() != nullptr) {
2103 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2104 mirror::Object* dex_elements_obj =
2105 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2106 GetObject(dex_path_list);
2107 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2108 // at the mCookie which is a DexFile vector.
2109 if (dex_elements_obj != nullptr) {
2110 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2111 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2112 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2113 mirror::Object* element = dex_elements->GetWithoutChecks(i);
2114 if (element == nullptr) {
2115 // Should never happen, fall back to java code to throw a NPE.
2116 break;
2117 }
2118 mirror::Object* dex_file = dex_file_field->GetObject(element);
2119 if (dex_file != nullptr) {
2120 const uint64_t cookie = cookie_field->GetLong(dex_file);
2121 auto* dex_files =
2122 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2123 if (dex_files == nullptr) {
2124 // This should never happen so log a warning.
2125 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2126 break;
2127 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002128 for (const DexFile* cp_dex_file : *dex_files) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002129 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002130 if (dex_class_def != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002131 RegisterDexFile(*cp_dex_file);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002132 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2133 *cp_dex_file, *dex_class_def);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002134 if (klass == nullptr) {
2135 CHECK(self->IsExceptionPending()) << descriptor;
2136 self->ClearException();
2137 return nullptr;
2138 }
2139 return klass;
2140 }
2141 }
2142 }
2143 }
2144 }
2145 }
Ian Rogers32427292014-11-19 14:05:21 -08002146 self->AssertNoPendingException();
2147 return nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002148 }
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002149}
2150
Ian Rogers98379392014-02-24 16:53:16 -08002151mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002152 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002153 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002154 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002155 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002156 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002157 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2158 // for primitive classes that aren't backed by dex files.
2159 return FindPrimitiveClass(descriptor[0]);
2160 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002161 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002162 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002163 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002164 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002165 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002166 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002167 // Class is not yet loaded.
2168 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002169 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002170 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002171 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002172 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002173 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002174 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002175 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002176 } else {
2177 // The boot class loader is searched ahead of the application class loader, failures are
2178 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2179 // trigger the chaining with a proper stack trace.
2180 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2181 self->SetException(ThrowLocation(), pre_allocated);
2182 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002183 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08002184 } else if (Runtime::Current()->UseCompileTimeClassPath()) {
Ian Rogers68b56852014-08-29 20:19:11 -07002185 // First try with the bootstrap class loader.
2186 if (class_loader.Get() != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002187 klass = LookupClass(self, descriptor, hash, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002188 if (klass != nullptr) {
2189 return EnsureResolved(self, descriptor, klass);
2190 }
2191 }
Ian Rogers63557452014-06-04 16:57:15 -07002192 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2193 // a NoClassDefFoundError being allocated.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002194 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002195 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002196 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002197 *pair.second);
Jesse Wilson47daf872011-11-23 11:42:45 -05002198 }
Ian Rogersbe7149f2013-08-20 09:29:39 -07002199 // Next try the compile time class path.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002200 const std::vector<const DexFile*>* class_path;
2201 {
Ian Rogersbe7149f2013-08-20 09:29:39 -07002202 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002203 ScopedLocalRef<jobject> jclass_loader(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002204 soa.AddLocalReference<jobject>(class_loader.Get()));
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002205 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2206 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002207 pair = FindInClassPath(descriptor, hash, *class_path);
Ian Rogers68b56852014-08-29 20:19:11 -07002208 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002209 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
Ian Rogers7b078e82014-09-10 14:44:24 -07002210 } else {
2211 // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2212 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2213 self->SetException(ThrowLocation(), pre_allocated);
2214 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002215 }
Jesse Wilson47daf872011-11-23 11:42:45 -05002216 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002217 ScopedObjectAccessUnchecked soa(self);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002218 mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2219 class_loader);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002220 if (cp_klass != nullptr) {
2221 return cp_klass;
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07002222 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002223 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002224 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08002225 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07002226 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07002227 {
2228 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002229 ScopedLocalRef<jobject> class_name_object(soa.Env(),
2230 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07002231 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07002232 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07002233 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07002234 }
Ian Rogers68b56852014-08-29 20:19:11 -07002235 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002236 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2237 WellKnownClasses::java_lang_ClassLoader_loadClass,
2238 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05002239 }
Ian Rogers98379392014-02-24 16:53:16 -08002240 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08002241 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07002242 return nullptr;
2243 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08002244 // broken loader - throw NPE to be compatible with Dalvik
Ian Rogers68b56852014-08-29 20:19:11 -07002245 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
Ian Rogers63557452014-06-04 16:57:15 -07002246 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07002247 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08002248 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002249 // success, return mirror::Class*
2250 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08002251 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002252 }
Ian Rogers07140832014-09-30 15:43:59 -07002253 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07002254}
2255
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002256mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002257 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002258 const DexFile& dex_file,
2259 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002260 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002261 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002262
Brian Carlstromaded5f72011-10-07 17:15:04 -07002263 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002264 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002265 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002266 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002267 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002268 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002269 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002270 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002271 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07002272 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2273 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002274 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002275 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002276 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002277 klass.Assign(GetClassRoot(kJavaLangReflectArtField));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002278 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002279 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002280 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002281 }
2282
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002283 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002284 // Allocate a class with the status of not ready.
2285 // Interface object should get the right size here. Regular class will
2286 // figure out the right size later and be replaced with one of the right
2287 // size when the class becomes resolved.
2288 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07002289 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002290 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002291 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07002292 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002293 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002294 klass->SetDexCache(FindDexCache(dex_file));
Ian Rogers7b078e82014-09-10 14:44:24 -07002295 LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002296 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002297 if (self->IsExceptionPending()) {
2298 // An exception occured during load, set status to erroneous while holding klass' lock in case
2299 // notification is necessary.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002300 if (!klass->IsErroneous()) {
2301 klass->SetStatus(mirror::Class::kStatusError, self);
2302 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002303 return nullptr;
2304 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002305 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002306
Mathieu Chartier590fee92013-09-13 13:46:47 -07002307 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002308 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07002309 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002310 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2311 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002312 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002313 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002314
Brian Carlstromaded5f72011-10-07 17:15:04 -07002315 // Finish loading (if necessary) by finding parents
2316 CHECK(!klass->IsLoaded());
2317 if (!LoadSuperAndInterfaces(klass, dex_file)) {
2318 // Loading failed.
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;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002323 }
2324 CHECK(klass->IsLoaded());
2325 // Link the class (if necessary)
2326 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07002327 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002328 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002329
2330 mirror::Class* new_class = nullptr;
2331 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07002332 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07002333 if (!klass->IsErroneous()) {
2334 klass->SetStatus(mirror::Class::kStatusError, self);
2335 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07002336 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002337 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07002338 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002339 CHECK(new_class != nullptr) << descriptor;
2340 CHECK(new_class->IsResolved()) << descriptor;
2341
2342 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002343
2344 /*
2345 * We send CLASS_PREPARE events to the debugger from here. The
2346 * definition of "preparation" is creating the static fields for a
2347 * class and initializing them to the standard default values, but not
2348 * executing any code (that comes later, during "initialization").
2349 *
2350 * We did the static preparation in LinkClass.
2351 *
2352 * The class has been prepared and resolved but possibly not yet verified
2353 * at this point.
2354 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002355 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08002356
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002357 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002358}
2359
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002360uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2361 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07002362 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002363 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07002364 size_t num_8 = 0;
2365 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002366 size_t num_32 = 0;
2367 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002368 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002369 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2370 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002371 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002372 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07002373 switch (c) {
2374 case 'L':
2375 case '[':
2376 num_ref++;
2377 break;
2378 case 'J':
2379 case 'D':
2380 num_64++;
2381 break;
2382 case 'I':
2383 case 'F':
2384 num_32++;
2385 break;
2386 case 'S':
2387 case 'C':
2388 num_16++;
2389 break;
2390 case 'B':
2391 case 'Z':
2392 num_8++;
2393 break;
2394 default:
2395 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002396 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002397 }
2398 }
2399 }
Fred Shih37f05ef2014-07-16 18:38:08 -07002400 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002401}
2402
Ian Rogers97b52f82014-08-14 11:34:07 -07002403OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2404 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002405 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01002406 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2407 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002408 *found = false;
2409 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002410 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002411 *found = true;
2412 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08002413}
2414
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002415static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2416 uint32_t method_idx) {
2417 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07002418 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002419 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002420 ClassDataItemIterator it(dex_file, class_data);
2421 // Skip fields
2422 while (it.HasNextStaticField()) {
2423 it.Next();
2424 }
2425 while (it.HasNextInstanceField()) {
2426 it.Next();
2427 }
2428 // Process methods
2429 size_t class_def_method_index = 0;
2430 while (it.HasNextDirectMethod()) {
2431 if (it.GetMemberIndex() == method_idx) {
2432 return class_def_method_index;
2433 }
2434 class_def_method_index++;
2435 it.Next();
2436 }
2437 while (it.HasNextVirtualMethod()) {
2438 if (it.GetMemberIndex() == method_idx) {
2439 return class_def_method_index;
2440 }
2441 class_def_method_index++;
2442 it.Next();
2443 }
2444 DCHECK(!it.HasNext());
2445 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08002446 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002447}
2448
Ian Rogers97b52f82014-08-14 11:34:07 -07002449const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08002450 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08002451 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002452 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08002453 size_t oat_method_index;
2454 if (method->IsStatic() || method->IsDirect()) {
2455 // Simple case where the oat method index was stashed at load time.
2456 oat_method_index = method->GetMethodIndex();
2457 } else {
2458 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2459 // by search for its position in the declared virtual methods.
2460 oat_method_index = declaring_class->NumDirectMethods();
2461 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002462 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002463 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07002464 // Check method index instead of identity in case of duplicate method definitions.
2465 if (method->GetDexMethodIndex() ==
2466 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002467 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002468 break;
2469 }
Ian Rogersf320b632012-03-13 18:47:47 -07002470 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08002471 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002472 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2473 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002474 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002475 DCHECK_EQ(oat_method_index,
2476 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002477 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002478 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07002479 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2480 declaring_class->GetDexClassDefIndex(),
2481 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002482 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002483 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002484 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002485 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07002486}
2487
2488// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002489const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002490 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07002491 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002492 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07002493 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002494 bool found;
2495 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002496 const void* result = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002497 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002498 result = oat_method.GetQuickCode();
2499 }
2500
Ian Rogersef7d42f2014-01-06 12:55:46 -08002501 if (result == nullptr) {
Ian Rogers1a570662014-03-12 01:02:21 -07002502 if (method->IsNative()) {
2503 // No code and native? Use generic trampoline.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002504 result = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002505 } else if (method->IsPortableCompiled()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002506 // No code? Do we expect portable code?
2507 result = GetQuickToPortableBridge();
2508 } else {
2509 // No code? You must mean to go into the interpreter.
2510 result = GetQuickToInterpreterBridge();
2511 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002512 }
2513 return result;
TDYa12785321912012-04-01 15:24:56 -07002514}
2515
Ian Rogersef7d42f2014-01-06 12:55:46 -08002516const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2517 bool* have_portable_code) {
2518 CHECK(!method->IsAbstract()) << PrettyMethod(method);
2519 *have_portable_code = false;
2520 if (method->IsProxyMethod()) {
2521 return GetPortableProxyInvokeHandler();
2522 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002523 bool found;
2524 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002525 const void* result = nullptr;
2526 const void* quick_code = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002527 if (found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002528 result = oat_method.GetPortableCode();
2529 quick_code = oat_method.GetQuickCode();
2530 }
2531
Ian Rogersef7d42f2014-01-06 12:55:46 -08002532 if (result == nullptr) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002533 if (quick_code == nullptr) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002534 // No code? You must mean to go into the interpreter.
2535 result = GetPortableToInterpreterBridge();
2536 } else {
2537 // No code? But there's quick code, so use a bridge.
2538 result = GetPortableToQuickBridge();
2539 }
2540 } else {
2541 *have_portable_code = true;
2542 }
2543 return result;
2544}
2545
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07002546const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2547 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2548 return nullptr;
2549 }
2550 bool found;
2551 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2552 return found ? oat_method.GetQuickCode() : nullptr;
2553}
2554
2555const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2556 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2557 return nullptr;
2558 }
2559 bool found;
2560 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2561 return found ? oat_method.GetPortableCode() : nullptr;
2562}
2563
Ian Rogersef7d42f2014-01-06 12:55:46 -08002564const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2565 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002566 bool found;
2567 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2568 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002569 return nullptr;
2570 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002571 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002572 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08002573}
2574
2575const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2576 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002577 bool found;
2578 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2579 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002580 return nullptr;
2581 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002582 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002583 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07002584}
2585
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002586// Returns true if the method must run with interpreter, false otherwise.
Brian Carlstromf3632832014-05-20 15:36:53 -07002587static bool NeedsInterpreter(
2588 mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2589 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002590 if ((quick_code == nullptr) && (portable_code == nullptr)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002591 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002592 // May return true for native code, in the case of generic JNI
2593 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002594 return true;
2595 }
Dragos Sbirlea90af14d2013-08-15 17:50:16 -07002596#ifdef ART_SEA_IR_MODE
2597 ScopedObjectAccess soa(Thread::Current());
2598 if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2599 LOG(INFO) << "Found " << PrettyMethod(method);
2600 return false;
2601 }
2602#endif
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002603 // If interpreter mode is enabled, every method (except native and proxy) must
2604 // be run with interpreter.
2605 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2606 !method->IsNative() && !method->IsProxyMethod();
2607}
2608
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002609void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002610 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002611 if (klass->NumDirectMethods() == 0) {
2612 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002613 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002614 Runtime* runtime = Runtime::Current();
2615 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002616 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2617 return; // OAT file unavailable.
2618 }
Ian Rogers19846512012-02-24 11:42:47 -08002619 }
Alex Light64ad14d2014-08-19 14:23:13 -07002620
Mathieu Chartierf8322842014-05-16 10:59:25 -07002621 const DexFile& dex_file = klass->GetDexFile();
2622 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002623 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002624 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002625 // There should always be class data if there were direct methods.
2626 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002627 ClassDataItemIterator it(dex_file, class_data);
2628 // Skip fields
2629 while (it.HasNextStaticField()) {
2630 it.Next();
2631 }
2632 while (it.HasNextInstanceField()) {
2633 it.Next();
2634 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002635 bool has_oat_class;
2636 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2637 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002638 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002639 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002640 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002641 if (!method->IsStatic()) {
2642 // Only update static methods.
2643 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002644 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002645 const void* portable_code = nullptr;
2646 const void* quick_code = nullptr;
2647 if (has_oat_class) {
2648 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2649 portable_code = oat_method.GetPortableCode();
2650 quick_code = oat_method.GetQuickCode();
2651 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002652 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2653 bool have_portable_code = false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002654 if (enter_interpreter) {
2655 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002656 // Check whether the method is native, in which case it's generic JNI.
Andreas Gampe2da88232014-02-27 12:26:20 -08002657 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002658 quick_code = GetQuickGenericJniStub();
Ian Rogers1a570662014-03-12 01:02:21 -07002659 portable_code = GetPortableToQuickBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002660 } else {
Ian Rogers1a570662014-03-12 01:02:21 -07002661 portable_code = GetPortableToInterpreterBridge();
Andreas Gampe2da88232014-02-27 12:26:20 -08002662 quick_code = GetQuickToInterpreterBridge();
2663 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002664 } else {
2665 if (portable_code == nullptr) {
2666 portable_code = GetPortableToQuickBridge();
2667 } else {
2668 have_portable_code = true;
2669 }
2670 if (quick_code == nullptr) {
2671 quick_code = GetQuickToPortableBridge();
2672 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002673 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002674 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2675 have_portable_code);
Ian Rogers19846512012-02-24 11:42:47 -08002676 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002677 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002678}
2679
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002680void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002681 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002682 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002683 Runtime* runtime = Runtime::Current();
2684 if (runtime->IsCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002685 // The following code only applies to a non-compiler runtime.
2686 return;
2687 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002688 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002689 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2690 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002691 if (oat_class != nullptr) {
2692 // Every kind of method should at least get an invoke stub from the oat_method.
2693 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002694 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002695 oat_method.LinkMethod(method.Get());
2696 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002697
Jeff Hao16743632013-05-08 10:59:04 -07002698 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002699 bool enter_interpreter = NeedsInterpreter(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002700 method->GetEntryPointFromQuickCompiledCode(),
2701 method->GetEntryPointFromPortableCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002702 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002703 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002704 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002705 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002706 }
2707
Brian Carlstrom92827a52011-10-10 15:50:01 -07002708 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002709 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2710 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002711 return;
2712 }
Ian Rogers19846512012-02-24 11:42:47 -08002713
Ian Rogersef7d42f2014-01-06 12:55:46 -08002714 bool have_portable_code = false;
Ian Rogers19846512012-02-24 11:42:47 -08002715 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002716 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002717 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2718 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002719 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2720 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002721 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002722 if (!method->IsNative()) {
2723 // Set entry point from compiled code if there's no code or in interpreter only mode.
2724 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2725 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2726 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002727 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002728 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2729 }
Ian Rogersef7d42f2014-01-06 12:55:46 -08002730 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2731 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2732 have_portable_code = true;
2733 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2734 } else {
2735 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2736 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
Ian Rogers0d6de042012-02-29 08:50:26 -08002737 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002738
Ian Rogers62d6c772013-02-27 08:32:07 -08002739 if (method->IsNative()) {
2740 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002741 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002742
2743 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002744 // We have a native method here without code. Then it should have either the generic JNI
2745 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2746 // TODO: this doesn't handle all the cases where trampolines may be installed.
2747 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2748 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002749 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002750 }
Ian Rogersf3e98552013-03-20 15:49:49 -07002751
Ian Rogers62d6c772013-02-27 08:32:07 -08002752 // Allow instrumentation its chance to hijack code.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002753 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
Ian Rogersef7d42f2014-01-06 12:55:46 -08002754 method->GetEntryPointFromQuickCompiledCode(),
2755 method->GetEntryPointFromPortableCompiledCode(),
2756 have_portable_code);
Brian Carlstrom92827a52011-10-10 15:50:01 -07002757}
2758
Fred Shih37f05ef2014-07-16 18:38:08 -07002759
Fred Shih37f05ef2014-07-16 18:38:08 -07002760
Ian Rogers7b078e82014-09-10 14:44:24 -07002761void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
Brian Carlstromf615a612011-07-23 12:50:34 -07002762 const DexFile::ClassDef& dex_class_def,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002763 Handle<mirror::Class> klass,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002764 mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002765 CHECK(klass.Get() != nullptr);
2766 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002767 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002768 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002769 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002770
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002771 klass->SetClass(GetClassRoot(kJavaLangClass));
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002772 if (kUseBakerOrBrooksReadBarrier) {
2773 klass->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002774 }
Andreas Gampe51829322014-08-25 15:05:04 -07002775 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002776 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002777 klass->SetAccessFlags(access_flags);
2778 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002779 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002780 klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002781
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002782 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002783 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002784 CHECK(klass->GetDexCacheStrings() != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002785
Ian Rogers13735952014-10-08 12:43:28 -07002786 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002787 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002788 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002789 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002790
Ian Rogers97b52f82014-08-14 11:34:07 -07002791
2792 bool has_oat_class = false;
2793 if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2794 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2795 &has_oat_class);
2796 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002797 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002798 }
2799 }
2800 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002801 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002802 }
2803}
2804
Ian Rogers7b078e82014-09-10 14:44:24 -07002805void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002806 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002807 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002808 const OatFile::OatClass* oat_class) {
2809 // Load fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002810 ClassDataItemIterator it(dex_file, class_data);
2811 if (it.NumStaticFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002812 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002813 if (UNLIKELY(statics == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002814 CHECK(self->IsExceptionPending()); // OOME.
2815 return;
2816 }
2817 klass->SetSFields(statics);
Ian Rogers0571d352011-11-03 19:51:38 -07002818 }
2819 if (it.NumInstanceFields() != 0) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002820 mirror::ObjectArray<mirror::ArtField>* fields =
2821 AllocArtFieldArray(self, it.NumInstanceFields());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002822 if (UNLIKELY(fields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002823 CHECK(self->IsExceptionPending()); // OOME.
2824 return;
2825 }
2826 klass->SetIFields(fields);
Ian Rogers0571d352011-11-03 19:51:38 -07002827 }
2828 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002829 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002830 StackHandleScope<1> hs(self);
2831 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002832 if (UNLIKELY(sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002833 CHECK(self->IsExceptionPending()); // OOME.
2834 return;
2835 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002836 klass->SetStaticField(i, sfield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002837 LoadField(dex_file, it, klass, sfield);
2838 }
2839 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002840 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002841 StackHandleScope<1> hs(self);
2842 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002843 if (UNLIKELY(ifield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002844 CHECK(self->IsExceptionPending()); // OOME.
2845 return;
2846 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002847 klass->SetInstanceField(i, ifield.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002848 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002849 }
2850
Ian Rogers0571d352011-11-03 19:51:38 -07002851 // Load methods.
2852 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002853 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002854 mirror::ObjectArray<mirror::ArtMethod>* directs =
2855 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002856 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002857 CHECK(self->IsExceptionPending()); // OOME.
2858 return;
2859 }
2860 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002861 }
Ian Rogers0571d352011-11-03 19:51:38 -07002862 if (it.NumVirtualMethods() != 0) {
2863 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002864 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2865 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002866 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002867 CHECK(self->IsExceptionPending()); // OOME.
2868 return;
2869 }
2870 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002871 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002872 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002873 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2874 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002875 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002876 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002877 StackHandleScope<1> hs(self);
2878 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002879 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002880 CHECK(self->IsExceptionPending()); // OOME.
2881 return;
2882 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002883 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002884 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002885 uint32_t it_method_index = it.GetMemberIndex();
2886 if (last_dex_method_index == it_method_index) {
2887 // duplicate case
2888 method->SetMethodIndex(last_class_def_method_index);
2889 } else {
2890 method->SetMethodIndex(class_def_method_index);
2891 last_dex_method_index = it_method_index;
2892 last_class_def_method_index = class_def_method_index;
2893 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002894 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002895 }
2896 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002897 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002898 StackHandleScope<1> hs(self);
2899 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002900 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002901 CHECK(self->IsExceptionPending()); // OOME.
2902 return;
2903 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002904 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002905 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002906 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002907 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002908 }
2909 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002910}
2911
Elliott Hughes1bac54f2012-03-16 12:48:31 -07002912void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002913 Handle<mirror::Class> klass,
2914 Handle<mirror::ArtField> dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002915 uint32_t field_idx = it.GetMemberIndex();
2916 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002917 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002918 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002919}
2920
Brian Carlstromea46f952013-07-30 01:26:50 -07002921mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002922 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002923 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002924 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002925 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002926 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002927
Brian Carlstromea46f952013-07-30 01:26:50 -07002928 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002929 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002930 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002931 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002932 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002933 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002934
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002935 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002936 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002937 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002938 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002939
Ian Rogers19846512012-02-24 11:42:47 -08002940 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002941 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002942
Andreas Gampe51829322014-08-25 15:05:04 -07002943 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002944
Ian Rogersdfb325e2013-10-30 01:00:44 -07002945 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002946 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002947 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2948 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002949 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002950 klass->SetFinalizable();
2951 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002952 std::string temp;
2953 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002954 // The Enum class declares a "final" finalize() method to prevent subclasses from
2955 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2956 // subclasses, so we exclude it here.
2957 // We also want to avoid setting the flag on Object, where we know that finalize() is
2958 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002959 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2960 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002961 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002962 }
2963 }
2964 }
2965 } else if (method_name[0] == '<') {
2966 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002967 bool is_init = (strcmp("<init>", method_name) == 0);
2968 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002969 if (UNLIKELY(!is_init && !is_clinit)) {
2970 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2971 } else {
2972 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2973 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002974 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002975 access_flags |= kAccConstructor;
2976 }
2977 }
2978 }
2979 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002980
Mathieu Chartier66f19252012-09-18 08:57:04 -07002981 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002982}
2983
Ian Rogers7b078e82014-09-10 14:44:24 -07002984void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002985 StackHandleScope<1> hs(self);
2986 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002987 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2988 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002989 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002990}
2991
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002992void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002993 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002994 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002995 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002996 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002997}
2998
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002999bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003000 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07003001 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003002 mirror::DexCache* dex_cache = GetDexCache(i);
3003 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08003004 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003005 }
3006 }
3007 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07003008}
3009
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003010bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003011 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07003012 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003013}
3014
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003015void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003016 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003017 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003018 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07003019 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3020 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003021 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07003022 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003023 if (log_new_dex_caches_roots_) {
3024 // TODO: This is not safe if we can remove dex caches.
3025 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3026 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003027}
3028
Brian Carlstromaded5f72011-10-07 17:15:04 -07003029void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07003030 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003031 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003032 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003033 if (IsDexFileRegisteredLocked(dex_file)) {
3034 return;
3035 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003036 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003037 // Don't alloc while holding the lock, since allocation may need to
3038 // suspend all threads and another thread may need the dex_lock_ to
3039 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003040 StackHandleScope<1> hs(self);
3041 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003042 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3043 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003044 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003045 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003046 if (IsDexFileRegisteredLocked(dex_file)) {
3047 return;
3048 }
3049 RegisterDexFileLocked(dex_file, dex_cache);
3050 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003051}
3052
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003053void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003054 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003055 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003056 RegisterDexFileLocked(dex_file, dex_cache);
3057}
3058
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003059mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003060 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003061 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07003062 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003063 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003064 if (dex_cache->GetDexFile() == &dex_file) {
3065 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003066 }
3067 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003068 // Search matching by location name.
3069 std::string location(dex_file.GetLocation());
3070 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003071 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003072 if (dex_cache->GetDexFile()->GetLocation() == location) {
3073 return dex_cache;
3074 }
3075 }
3076 // Failure, dump diagnostic and abort.
3077 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003078 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08003079 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3080 }
3081 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08003082 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003083}
3084
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003085void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003086 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08003087 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003088 mirror::DexCache* dex_cache = GetDexCache(i);
3089 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08003090 }
3091}
3092
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003093mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003094 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003095 if (UNLIKELY(klass == nullptr)) {
3096 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003097 }
3098 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003099}
3100
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003101mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3102 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003103 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07003104 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003105 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003106 StackHandleScope<1> hs(self);
3107 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003108 ObjectLock<mirror::Class> lock(self, h_class);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003109 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003110 primitive_class->SetPrimitiveType(type);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003111 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3112 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003113 mirror::Class* existing = InsertClass(descriptor, primitive_class,
3114 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003115 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003116 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07003117}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003118
Brian Carlstrombe977852011-07-19 14:54:54 -07003119// Create an array class (i.e. the class object for the array, not the
3120// array itself). "descriptor" looks like "[C" or "[[[[B" or
3121// "[Ljava/lang/String;".
3122//
3123// If "descriptor" refers to an array of primitives, look up the
3124// primitive type's internally-generated class object.
3125//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003126// "class_loader" is the class loader of the class that's referring to
3127// us. It's used to ensure that we're looking for the element type in
3128// the right context. It does NOT become the class loader for the
3129// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07003130//
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003131// Returns nullptr with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003132mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003133 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07003134 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003135 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003136 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003137 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3138 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003139 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003140 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003141 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003142 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3143 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07003144 if (component_type.Get() == nullptr) {
3145 DCHECK(self->IsExceptionPending());
3146 return nullptr;
3147 } else {
3148 self->ClearException();
3149 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003150 }
Ian Rogers2d10b202014-05-12 19:15:18 -07003151 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3152 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3153 return nullptr;
3154 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003155 // See if the component type is already loaded. Array classes are
3156 // always associated with the class loader of their underlying
3157 // element type -- an array of Strings goes with the loader for
3158 // java/lang/String -- so we need to look for it there. (The
3159 // caller should have checked for the existence of the class
3160 // before calling here, but they did so with *their* class loader,
3161 // not the component type's loader.)
3162 //
3163 // If we find it, the caller adds "loader" to the class' initiating
3164 // loader list, which should prevent us from going through this again.
3165 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003166 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003167 // are the same, because our caller (FindClass) just did the
3168 // lookup. (Even if we get this wrong we still have correct behavior,
3169 // because we effectively do this lookup again when we add the new
3170 // class to the hash table --- necessary because of possible races with
3171 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003172 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003173 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003174 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003175 return new_class;
3176 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003177 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003178
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003179 // Fill out the fields in the Class.
3180 //
3181 // It is possible to execute some methods against arrays, because
3182 // all arrays are subclasses of java_lang_Object_, so we need to set
3183 // up a vtable. We can just point at the one in java_lang_Object_.
3184 //
3185 // Array classes are simple enough that we don't need to do a full
3186 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003187 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003188 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003189 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003190 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003191 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003192 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003193 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003194 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003195 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003196 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003197 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003198 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003199 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003200 GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003201 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003202 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003203 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003204 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003205 new_class.Assign(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003206 }
3207 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003208 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003209 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003210 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003211 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003212 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003213 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003214 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003215 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003216 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003217 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003218 new_class->SetSuperClass(java_lang_Object);
3219 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003220 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003221 new_class->SetClassLoader(component_type->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003222 new_class->SetStatus(mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003223 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003224 StackHandleScope<mirror::Class::kImtSize> hs2(self,
3225 Runtime::Current()->GetImtUnimplementedMethod());
3226 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003227 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003228 new_class->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003229 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07003230 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003231
3232
3233 // All arrays have java/lang/Cloneable and java/io/Serializable as
3234 // interfaces. We need to set that up here, so that stuff like
3235 // "instanceof" works right.
3236 //
3237 // Note: The GC could run during the call to FindSystemClass,
3238 // so we need to make sure the class object is GC-valid while we're in
3239 // there. Do this by clearing the interface list so the GC will just
3240 // think that the entries are null.
3241
3242
3243 // Use the single, global copies of "interfaces" and "iftable"
3244 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003245 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07003246 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003247 CHECK(array_iftable != nullptr);
3248 new_class->SetIfTable(array_iftable);
3249 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003250
Elliott Hughes00626c22013-06-14 15:04:14 -07003251 // Inherit access flags from the component type.
3252 int access_flags = new_class->GetComponentType()->GetAccessFlags();
3253 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3254 access_flags &= kAccJavaFlagsMask;
3255 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003256 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07003257 access_flags |= kAccAbstract | kAccFinal;
3258 access_flags &= ~kAccInterface;
3259
3260 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003261
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003262 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08003263 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003264 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003265 }
3266 // Another thread must have loaded the class after we
3267 // started but before we finished. Abandon what we've
3268 // done.
3269 //
3270 // (Yes, this happens.)
3271
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003272 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07003273}
3274
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003275mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07003276 switch (type) {
3277 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003278 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07003279 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003280 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07003281 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003282 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07003283 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003284 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07003285 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003286 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07003287 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003288 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07003289 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003290 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07003291 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003292 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07003293 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07003294 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07003295 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003296 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07003297 }
Elliott Hughesbd935992011-08-22 11:59:34 -07003298 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003299 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003300 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003301}
3302
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003303mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3304 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08003305 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003306 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08003307 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003308 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08003309 source += " from ";
3310 source += dex_cache->GetLocation()->ToModifiedUtf8();
3311 }
3312 LOG(INFO) << "Loaded class " << descriptor << source;
3313 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003314 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003315 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003316 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003317 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07003318 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003319 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003320 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003321 // Check a class loaded with the system class loader matches one in the image if the class
3322 // is in the image.
3323 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003324 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003325 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003326 }
3327 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08003328 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003329 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08003330 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003331 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003332 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003333 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003334}
3335
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003336mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3337 size_t hash) {
3338 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003339 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3340 hash);
3341 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003342 CHECK(klass->IsProxyClass());
3343 return nullptr;
3344 }
3345
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003346 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003347 CHECK_NE(existing, klass) << descriptor;
3348 CHECK(!existing->IsResolved()) << descriptor;
3349 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3350
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003351 CHECK(!klass->IsTemp()) << descriptor;
3352 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3353 dex_cache_image_class_lookup_required_) {
3354 // Check a class loaded with the system class loader matches one in the image if the class
3355 // is in the image.
3356 existing = LookupClassFromImage(descriptor);
3357 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003358 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003359 }
3360 }
3361 VerifyObject(klass);
3362
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003363 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003364 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003365 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003366 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003367 }
3368
3369 return existing;
3370}
3371
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003372bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003373 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003374 auto pair = std::make_pair(descriptor, class_loader);
3375 auto it = class_table_.Find(pair);
3376 if (it != class_table_.end()) {
3377 class_table_.Erase(it);
3378 return true;
3379 }
3380 it = pre_zygote_class_table_.Find(pair);
3381 if (it != pre_zygote_class_table_.end()) {
3382 pre_zygote_class_table_.Erase(it);
3383 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08003384 }
3385 return false;
3386}
3387
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003388mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003389 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003390 {
Ian Rogers7b078e82014-09-10 14:44:24 -07003391 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003392 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003393 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003394 return result;
3395 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07003396 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003397 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3398 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003399 } else {
3400 // Lookup failed but need to search dex_caches_.
3401 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003402 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003403 InsertClass(descriptor, result, hash);
3404 } else {
3405 // Searching the image dex files/caches failed, we don't want to get into this situation
3406 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3407 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07003408 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003409 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3410 MoveImageClassesToClassTable();
3411 }
3412 }
3413 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003414 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08003415}
3416
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003417mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003418 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003419 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003420 auto descriptor_pair = std::make_pair(descriptor, class_loader);
3421 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3422 if (it == pre_zygote_class_table_.end()) {
3423 it = class_table_.FindWithHash(descriptor_pair, hash);
3424 if (it == class_table_.end()) {
3425 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07003426 }
3427 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003428 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003429}
3430
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003431static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3432 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3433 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003434 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003435 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3436 return root->AsObjectArray<mirror::DexCache>();
3437}
3438
3439void ClassLinker::MoveImageClassesToClassTable() {
3440 Thread* self = Thread::Current();
3441 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3442 if (!dex_cache_image_class_lookup_required_) {
3443 return; // All dex cache classes are already in the class table.
3444 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003445 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003446 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07003447 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003448 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3449 mirror::DexCache* dex_cache = dex_caches->Get(i);
3450 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3451 for (int32_t j = 0; j < types->GetLength(); j++) {
3452 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003453 if (klass != nullptr) {
3454 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07003455 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003456 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003457 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3458 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003459 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003460 << PrettyClassAndClassLoader(klass);
3461 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003462 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003463 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003464 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08003465 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003466 }
3467 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003468 }
3469 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003470 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003471}
3472
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003473void ClassLinker::MoveClassTableToPreZygote() {
3474 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3475 DCHECK(pre_zygote_class_table_.Empty());
3476 pre_zygote_class_table_ = std::move(class_table_);
3477 class_table_.Clear();
3478}
3479
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003480mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07003481 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003482 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3483 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3484 mirror::DexCache* dex_cache = dex_caches->Get(i);
3485 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00003486 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003487 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003488 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003489 const DexFile::TypeId* type_id =
3490 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003491 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003492 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3493 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003494 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003495 return klass;
3496 }
3497 }
3498 }
3499 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003500 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003501}
3502
3503void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3504 result.clear();
3505 if (dex_cache_image_class_lookup_required_) {
3506 MoveImageClassesToClassTable();
3507 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003508 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3509 while (true) {
3510 auto it = class_table_.Find(descriptor);
3511 if (it == class_table_.end()) {
3512 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003513 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08003514 result.push_back(it->Read());
3515 class_table_.Erase(it);
3516 }
3517 for (mirror::Class* k : result) {
3518 class_table_.Insert(GcRoot<mirror::Class>(k));
3519 }
3520 size_t pre_zygote_start = result.size();
3521 // Now handle the pre zygote table.
3522 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3523 // called from the debugger.
3524 while (true) {
3525 auto it = pre_zygote_class_table_.Find(descriptor);
3526 if (it == pre_zygote_class_table_.end()) {
3527 break;
3528 }
3529 result.push_back(it->Read());
3530 pre_zygote_class_table_.Erase(it);
3531 }
3532 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3533 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08003534 }
3535}
3536
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003537void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003538 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003539 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08003540
Ian Rogers9ffb0392012-09-10 11:56:50 -07003541 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003542 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003543 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07003544 return;
3545 }
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003546 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3547 return;
3548 }
jeffhao98eacac2011-09-14 16:11:53 -07003549
Ian Rogers9ffb0392012-09-10 11:56:50 -07003550 // The class might already be erroneous, for example at compile time if we attempted to verify
3551 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003552 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003553 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08003554 return;
3555 }
3556
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003557 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003558 klass->SetStatus(mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003559 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003560 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003561 << PrettyClass(klass.Get());
Ian Rogers9ffb0392012-09-10 11:56:50 -07003562 CHECK(!Runtime::Current()->IsCompiler());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003563 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07003564 }
jeffhao98eacac2011-09-14 16:11:53 -07003565
Jeff Hao4a200f52014-04-01 14:58:49 -07003566 // Skip verification if disabled.
3567 if (!Runtime::Current()->IsVerificationEnabled()) {
3568 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07003569 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07003570 return;
3571 }
3572
Ian Rogers9ffb0392012-09-10 11:56:50 -07003573 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003574 StackHandleScope<2> hs(self);
3575 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003576 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07003577 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003578 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003579
3580 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003581 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003582 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07003583 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07003584 std::string error_msg(
3585 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3586 PrettyDescriptor(klass.Get()).c_str(),
3587 PrettyDescriptor(super.Get()).c_str()));
Ian Rogers1c5eb702012-02-01 09:18:34 -08003588 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003589 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3590 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08003591 self->ClearException();
3592 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003593 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3594 if (cause.Get() != nullptr) {
3595 self->GetException(nullptr)->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08003596 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08003597 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00003598 if (Runtime::Current()->IsCompiler()) {
3599 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3600 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003601 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08003602 return;
3603 }
3604 }
3605
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003606 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07003607 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003608 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003609 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003610 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003611 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003612 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003613 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003614 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3615 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003616 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07003617 return;
3618 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003619 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08003620 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07003621 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003622 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003623 Runtime::Current()->IsCompiler(),
3624 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07003625 }
3626 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07003627 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003628 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07003629 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3630 << " because: " << error_msg;
3631 }
Ian Rogers1f539342012-10-03 21:09:42 -07003632 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003633 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003634 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003635 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003636 // Even though there were no verifier failures we need to respect whether the super-class
3637 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003638 if (super.Get() == nullptr || super->IsVerified()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003639 klass->SetStatus(mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003640 } else {
3641 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003642 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003643 // Pretend a soft failure occured so that we don't consider the class verified below.
3644 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003645 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003646 } else {
3647 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3648 // Soft failures at compile time should be retried at runtime. Soft
3649 // failures at runtime will be handled by slow paths in the generated
3650 // code. Set status accordingly.
3651 if (Runtime::Current()->IsCompiler()) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003652 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003653 } else {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003654 klass->SetStatus(mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003655 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3656 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003657 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003658 }
3659 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003660 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003661 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003662 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3663 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003664 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003665 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003666 klass->SetStatus(mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003667 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003668 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003669 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003670 // Let the interpreter know it by setting the kAccPreverified flag onto each
3671 // method.
3672 // Note: we're going here during compilation and at runtime. When we set the
3673 // kAccPreverified flag when compiling image classes, the flag is recorded
3674 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003675 EnsurePreverifiedMethods(klass);
3676 }
3677}
3678
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003679void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003680 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003681 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003682 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003683 }
jeffhao98eacac2011-09-14 16:11:53 -07003684}
3685
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003686bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3687 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003688 // If we're compiling, we can only verify the class using the oat file if
3689 // we are not compiling the image or if the class we're verifying is not part of
3690 // the app. In other words, we will only check for preverification of bootclasspath
3691 // classes.
3692 if (Runtime::Current()->IsCompiler()) {
3693 // Are we compiling the bootclasspath?
3694 if (!Runtime::Current()->UseCompileTimeClassPath()) {
3695 return false;
3696 }
3697 // We are compiling an app (not the image).
3698
3699 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003700 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003701 return false;
3702 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003703 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003704
Vladimir Markoaa4497d2014-09-05 14:01:17 +01003705 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003706 // In case we run without an image there won't be a backing oat file.
3707 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003708 return false;
3709 }
3710
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003711 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003712 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003713 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3714 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003715 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003716 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003717 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003718 // Compile time verification failed with a soft error. Compile time verification can fail
3719 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003720 // class ... {
3721 // Foo x;
3722 // .... () {
3723 // if (...) {
3724 // v1 gets assigned a type of resolved class Foo
3725 // } else {
3726 // v1 gets assigned a type of unresolved class Bar
3727 // }
3728 // iput x = v1
3729 // } }
3730 // when we merge v1 following the if-the-else it results in Conflict
3731 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3732 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3733 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3734 // at compile time).
3735 return false;
3736 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003737 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003738 // Compile time verification failed with a hard error. This is caused by invalid instructions
3739 // in the class. These errors are unrecoverable.
3740 return false;
3741 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003742 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003743 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3744 // not loading the class.
3745 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3746 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003747 return false;
3748 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003749 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003750 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003751 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003752 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003753 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003754}
3755
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003756void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003757 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003758 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3759 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3760 }
3761 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3762 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3763 }
3764}
3765
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003766void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003767 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003768 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3769 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003770 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003771 return; // native or abstract method
3772 }
3773 if (code_item->tries_size_ == 0) {
3774 return; // nothing to process
3775 }
Ian Rogers13735952014-10-08 12:43:28 -07003776 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003777 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3778 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3779 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3780 CatchHandlerIterator iterator(handlers_ptr);
3781 for (; iterator.HasNext(); iterator.Next()) {
3782 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3783 // unresolved exception types will be ignored by exception delivery
3784 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003785 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003786 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003787 DCHECK(Thread::Current()->IsExceptionPending());
3788 Thread::Current()->ClearException();
3789 }
3790 }
3791 }
3792 handlers_ptr = iterator.EndDataPointer();
3793 }
3794}
3795
Brian Carlstromea46f952013-07-30 01:26:50 -07003796static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003797static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3798 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003799
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003800mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003801 jobjectArray interfaces, jobject loader,
3802 jobjectArray methods, jobjectArray throws) {
3803 Thread* self = soa.Self();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003804 StackHandleScope<8> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003805 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003806 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003807 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003808 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003809 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003810 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003811 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003812 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003813 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3814 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003815 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003816 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003817 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003818 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003819 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003820 klass->SetStatus(mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003821
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003822 // Instance fields are inherited, but we add a couple of static fields...
Ian Rogersa436fde2013-08-27 23:34:06 -07003823 {
3824 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003825 if (UNLIKELY(sfields == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003826 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003827 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003828 }
3829 klass->SetSFields(sfields);
3830 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003831 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3832 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003833 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3834 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003835 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003836 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003837 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003838 klass->SetStaticField(0, interfaces_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003839 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003840 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003841 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3842 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003843 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3844 if (UNLIKELY(throws_sfield.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003845 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003846 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003847 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003848 klass->SetStaticField(1, throws_sfield.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003849 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003850 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003851 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003852
Ian Rogers466bb252011-10-14 03:29:56 -07003853 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003854 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003855 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003856 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003857 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003858 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003859 }
3860 klass->SetDirectMethods(directs);
3861 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003862 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003863 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003864 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003865 }
3866 klass->SetDirectMethod(0, constructor);
3867 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003868
Mathieu Chartier590fee92013-09-13 13:46:47 -07003869 // Create virtual method using specified prototypes.
3870 size_t num_virtual_methods =
3871 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003872 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003873 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3874 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003875 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003876 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003877 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003878 }
3879 klass->SetVirtualMethods(virtuals);
3880 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003881 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003882 StackHandleScope<1> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003883 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3884 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003885 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
Ian Rogersa436fde2013-08-27 23:34:06 -07003886 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003887 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003888 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003889 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003890 }
3891 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003892 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003893
3894 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Brian Carlstromf3632832014-05-20 15:36:53 -07003895 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003896 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003897
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003898 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3899 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003900 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003901 // Must hold lock on object when resolved.
3902 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003903 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003904 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003905 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003906 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003907 klass->SetStatus(mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003908 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003909 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003910 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003911
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003912 CHECK(klass->IsRetired());
3913 CHECK_NE(klass.Get(), new_class);
3914 klass.Assign(new_class);
3915
3916 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003917 interfaces_sfield->SetObject<false>(klass.Get(),
3918 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003919 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003920 throws_sfield->SetObject<false>(klass.Get(),
3921 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003922
3923 {
3924 // Lock on klass is released. Lock new class object.
3925 ObjectLock<mirror::Class> initialization_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003926 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003927 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003928
3929 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003930 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003931 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003932 CheckProxyConstructor(klass->GetDirectMethod(0));
3933 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003934 StackHandleScope<2> hs2(self);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003935 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3936 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003937 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3938 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003939 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003940 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003941
Mathieu Chartier590fee92013-09-13 13:46:47 -07003942 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003943 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003944 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003945 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3946
3947 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003948 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003949 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003950
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003951 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003952 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003953 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003954 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003955 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003956 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3957 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003958 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003959 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003960}
3961
Ian Rogersef7d42f2014-01-06 12:55:46 -08003962std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003963 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003964 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003965 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003966 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3967}
3968
Ian Rogersef7d42f2014-01-06 12:55:46 -08003969mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3970 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003971 DCHECK(proxy_class->IsProxyClass());
3972 DCHECK(proxy_method->IsProxyMethod());
3973 // Locate the dex cache of the original interface/Object
Andreas Gampe58a5af82014-07-31 16:23:49 -07003974 mirror::DexCache* dex_cache = nullptr;
Ian Rogers16f93672012-02-14 12:29:06 -08003975 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003976 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers16f93672012-02-14 12:29:06 -08003977 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003978 mirror::DexCache* a_dex_cache = GetDexCache(i);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003979 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07003980 dex_cache = a_dex_cache;
Ian Rogers16f93672012-02-14 12:29:06 -08003981 break;
3982 }
3983 }
3984 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07003985 CHECK(dex_cache != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003986 uint32_t method_idx = proxy_method->GetDexMethodIndex();
Brian Carlstromea46f952013-07-30 01:26:50 -07003987 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07003988 CHECK(resolved_method != nullptr);
Ian Rogers16f93672012-02-14 12:29:06 -08003989 return resolved_method;
3990}
3991
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003992
Brian Carlstromea46f952013-07-30 01:26:50 -07003993mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003994 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003995 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003996 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003997 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003998 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003999 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
4000 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02004001 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4002 // constructor method.
4003 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
4004 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07004005 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4006 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07004007 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
4008 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004009 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07004010 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004011 }
Ian Rogers466bb252011-10-14 03:29:56 -07004012 // Make this constructor public and fix the class to be our Proxy version
4013 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004014 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08004015 return constructor;
4016}
4017
Brian Carlstromea46f952013-07-30 01:26:50 -07004018static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004019 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004020 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004021 CHECK_STREQ(constructor->GetName(), "<init>");
4022 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4023 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07004024 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04004025}
4026
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004027mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004028 Handle<mirror::Class> klass,
4029 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004030 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4031 // prototype method
Ian Rogers16f93672012-02-14 12:29:06 -08004032 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004033 prototype.Get());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004034 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07004035 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07004036 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004037 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004038 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004039 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004040 }
Ian Rogers466bb252011-10-14 03:29:56 -07004041
4042 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4043 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004044 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07004045 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004046
Ian Rogers466bb252011-10-14 03:29:56 -07004047 // At runtime the method looks like a reference and argument saving method, clone the code
4048 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08004049 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4050 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07004051 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08004052
Ian Rogersc2b44472011-12-14 21:17:17 -08004053 return method;
4054}
Jesse Wilson95caa792011-10-12 18:14:17 -04004055
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004056static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4057 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004058 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07004059 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004060 CHECK(!prototype->IsFinal());
4061 CHECK(method->IsFinal());
4062 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08004063
4064 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4065 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07004066 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4067 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Ian Rogers19846512012-02-24 11:42:47 -08004068 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4069
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004070 CHECK_STREQ(method->GetName(), prototype->GetName());
4071 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07004072 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07004073 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04004074}
4075
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004076static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4077 bool can_init_parents)
4078 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004079 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004080 return true;
4081 }
4082 if (!can_init_statics) {
4083 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07004084 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004085 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004086 return false;
4087 }
4088 // Check if there are encoded static values needing initialization.
4089 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004090 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004091 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004092 if (dex_class_def->static_values_off_ != 0) {
4093 return false;
4094 }
4095 }
4096 }
4097 if (!klass->IsInterface() && klass->HasSuperClass()) {
4098 mirror::Class* super_class = klass->GetSuperClass();
4099 if (!can_init_parents && !super_class->IsInitialized()) {
4100 return false;
4101 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08004102 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004103 return false;
4104 }
4105 }
4106 }
4107 return true;
4108}
4109
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004110bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07004111 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004112 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4113
4114 // Are we already initialized and therefore done?
4115 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4116 // an initialized class will never change its state.
4117 if (klass->IsInitialized()) {
4118 return true;
4119 }
4120
4121 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004122 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004123 return false;
4124 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004125
Ian Rogers7b078e82014-09-10 14:44:24 -07004126 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004127 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004128 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004129 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004130
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004131 // Re-check under the lock in case another thread initialized ahead of us.
4132 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004133 return true;
4134 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004135
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004136 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004137 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004138 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004139 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004140 return false;
4141 }
4142
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004143 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004144
4145 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004146 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004147 if (!klass->IsVerified()) {
4148 // We failed to verify, expect either the klass to be erroneous or verification failed at
4149 // compile time.
4150 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07004151 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004152 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004153 } else {
4154 CHECK(Runtime::Current()->IsCompiler());
4155 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07004156 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004157 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07004158 } else {
4159 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004160 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004161 }
4162
Brian Carlstromd1422f82011-09-28 11:37:09 -07004163 // If the class is kStatusInitializing, either this thread is
4164 // initializing higher up the stack or another thread has beat us
4165 // to initializing and we need to wait. Either way, this
4166 // invocation of InitializeClass will not be responsible for
4167 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004168 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07004169 // Could have got an exception during verification.
4170 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004171 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004172 return false;
4173 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07004174 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07004175 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004176 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004177 return true;
4178 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004179 // No. That's fine. Wait for another thread to finish initializing.
4180 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004181 }
4182
4183 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004184 klass->SetStatus(mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004185 return false;
4186 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004187 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004188
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004189 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004190
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004191 // From here out other threads may observe that we're initializing and so changes of state
4192 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07004193 klass->SetClinitThreadId(self->GetTid());
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004194 klass->SetStatus(mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004195
4196 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004197 }
4198
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07004199 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004200 if (!klass->IsInterface() && klass->HasSuperClass()) {
4201 mirror::Class* super_class = klass->GetSuperClass();
4202 if (!super_class->IsInitialized()) {
4203 CHECK(!super_class->IsInterface());
4204 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004205 StackHandleScope<1> hs(self);
4206 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07004207 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004208 if (!super_initialized) {
4209 // The super class was verified ahead of entering initializing, we should only be here if
4210 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004211 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07004212 << "Super class initialization failed for "
4213 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004214 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004215 << "\nPending exception:\n"
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004216 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004217 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004218 // Initialization failed because the super-class is erroneous.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004219 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004220 return false;
4221 }
Ian Rogers1bddec32012-02-04 12:27:34 -08004222 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004223 }
4224
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004225 const size_t num_static_fields = klass->NumStaticFields();
4226 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07004227 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004228 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07004229 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07004230 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004231 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07004232 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004233
4234 // Eagerly fill in static fields so that the we don't have to do as many expensive
4235 // Class::FindStaticField in ResolveField.
4236 for (size_t i = 0; i < num_static_fields; ++i) {
4237 mirror::ArtField* field = klass->GetStaticField(i);
4238 const uint32_t field_idx = field->GetDexFieldIndex();
4239 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4240 if (resolved_field == nullptr) {
4241 dex_cache->SetResolvedField(field_idx, field);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004242 } else {
4243 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07004244 }
4245 }
4246
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004247 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4248 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07004249 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004250 ClassDataItemIterator field_it(dex_file, class_data);
4251 if (value_it.HasNext()) {
4252 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004253 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004254 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004255 StackHandleScope<1> hs2(self);
4256 Handle<mirror::ArtField> field(hs2.NewHandle(
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004257 ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004258 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004259 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004260 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004261 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01004262 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07004263 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004264 }
4265 }
4266 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004267
Ian Rogersd91d6d62013-09-25 20:26:14 -07004268 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004269 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004270 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07004271 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004272 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004273 }
4274
Ian Rogers7b078e82014-09-10 14:44:24 -07004275 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004276 uint64_t t1 = NanoTime();
4277
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004278 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004279 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07004280 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004281
4282 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004283 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004284 klass->SetStatus(mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004285 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004286 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07004287 RuntimeStats* global_stats = Runtime::Current()->GetStats();
4288 RuntimeStats* thread_stats = self->GetStats();
4289 ++global_stats->class_init_count;
4290 ++thread_stats->class_init_count;
4291 global_stats->class_init_time_ns += (t1 - t0);
4292 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07004293 // Set the class as initialized except if failed to initialize static fields.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004294 klass->SetStatus(mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004295 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07004296 std::string temp;
4297 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07004298 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08004299 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08004300 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004301 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004302 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004303 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08004304 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004305}
4306
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004307bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004308 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07004309 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004310 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004311 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004312 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08004313 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004314
4315 // When we wake up, repeat the test for init-in-progress. If
4316 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07004317 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07004318 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07004319 WrapExceptionInInitializer(klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004320 klass->SetStatus(mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004321 return false;
4322 }
4323 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004324 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07004325 continue;
4326 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004327 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07004328 // Compile time initialization failed.
4329 return false;
4330 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07004331 if (klass->IsErroneous()) {
4332 // The caller wants an exception, but it was thrown in a
4333 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07004334 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004335 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07004336 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07004337 return false;
4338 }
4339 if (klass->IsInitialized()) {
4340 return true;
4341 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004342 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004343 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004344 }
Ian Rogers07140832014-09-30 15:43:59 -07004345 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07004346}
4347
Ian Rogersb5fb2072014-12-02 17:22:02 -08004348static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4349 Handle<mirror::ArtMethod> method1,
4350 Handle<mirror::ArtMethod> method2)
4351 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4352 {
4353 StackHandleScope<1> hs(self);
4354 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
4355 if (UNLIKELY(method2->GetReturnType() != return_type.Get())) {
4356 return false;
4357 }
4358 }
4359 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4360 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4361 if (types1 == nullptr) {
4362 return (types2 == nullptr) || (types2->Size() == 0);
4363 } else if (UNLIKELY(types2 == nullptr)) {
4364 return types1->Size() == 0;
4365 }
4366 uint32_t num_types = types1->Size();
4367 if (UNLIKELY(num_types != types2->Size())) {
4368 return false;
4369 }
4370 for (uint32_t i = 0; i < num_types; ++i) {
4371 mirror::Class* param_type =
4372 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true);
4373 mirror::Class* other_param_type =
4374 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
4375 if (UNLIKELY(param_type != other_param_type)) {
4376 return false;
4377 }
4378 }
4379 return true;
4380}
4381
4382
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004383bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004384 if (klass->IsInterface()) {
4385 return true;
4386 }
Ian Rogers151f2212014-05-06 11:27:27 -07004387 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07004388 Thread* self = Thread::Current();
4389 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08004390 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
4391 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004392 if (klass->HasSuperClass() &&
4393 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004394 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004395 h_m.Assign(klass->GetVTableEntry(i));
4396 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
4397 if (h_m.Get() != super_h_m.Get() &&
4398 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004399 ThrowLinkageError(klass.Get(),
4400 "Class %s method %s resolves differently in superclass %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004401 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004402 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004403 PrettyDescriptor(klass->GetSuperClass()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004404 return false;
4405 }
4406 }
4407 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004408 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07004409 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4410 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4411 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08004412 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4413 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
4414 if (h_m.Get() != super_h_m.Get() &&
4415 !HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m)) {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004416 ThrowLinkageError(klass.Get(),
4417 "Class %s method %s resolves differently in interface %s",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004418 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogersb5fb2072014-12-02 17:22:02 -08004419 PrettyMethod(h_m.Get()).c_str(),
Ian Rogers151f2212014-05-06 11:27:27 -07004420 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004421 return false;
4422 }
4423 }
4424 }
4425 }
4426 return true;
4427}
4428
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004429bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4430 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004431 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004432 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07004433 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004434 return true;
4435 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004436 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07004437 if (!success) {
4438 if (can_init_fields && can_init_parents) {
4439 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4440 }
4441 } else {
4442 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08004443 }
4444 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07004445}
4446
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004447void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4448 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4449 if (fields != nullptr) {
4450 for (int index = 0; index < fields->GetLength(); index ++) {
4451 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4452 fields->Get(index)->SetDeclaringClass(new_class);
4453 }
4454 }
4455 }
4456
4457 fields = new_class->GetSFields();
4458 if (fields != nullptr) {
4459 for (int index = 0; index < fields->GetLength(); index ++) {
4460 if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4461 fields->Get(index)->SetDeclaringClass(new_class);
4462 }
4463 }
4464 }
4465
4466 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4467 if (methods != nullptr) {
4468 for (int index = 0; index < methods->GetLength(); index ++) {
4469 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4470 methods->Get(index)->SetDeclaringClass(new_class);
4471 }
4472 }
4473 }
4474
4475 methods = new_class->GetVirtualMethods();
4476 if (methods != nullptr) {
4477 for (int index = 0; index < methods->GetLength(); index ++) {
4478 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4479 methods->Get(index)->SetDeclaringClass(new_class);
4480 }
4481 }
4482 }
4483}
4484
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004485bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4486 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004487 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004488 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004489
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004490 if (!LinkSuperClass(klass)) {
4491 return false;
4492 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004493 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4494 self, Runtime::Current()->GetImtUnimplementedMethod());
4495 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004496 return false;
4497 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004498 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004499 return false;
4500 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004501 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07004502 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07004503 return false;
4504 }
4505 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004506 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004507
4508 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4509 // We don't need to retire this class as it has no embedded tables or it was created the
4510 // correct size during class linker initialization.
4511 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4512
4513 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004514 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004515 }
4516
4517 // This will notify waiters on klass that saw the not yet resolved
4518 // class in the class_table_ during EnsureResolved.
4519 klass->SetStatus(mirror::Class::kStatusResolved, self);
4520 *new_class = klass.Get();
4521 } else {
4522 CHECK(!klass->IsResolved());
4523 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004524 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004525 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004526 CHECK(self->IsExceptionPending()); // Expect an OOME.
4527 klass->SetStatus(mirror::Class::kStatusError, self);
4528 return false;
4529 }
4530
4531 CHECK_EQ((*new_class)->GetClassSize(), class_size);
4532 StackHandleScope<1> hs(self);
4533 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4534 ObjectLock<mirror::Class> lock(self, new_class_h);
4535
4536 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4537
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004538 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4539 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004540 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004541
4542 // This will notify waiters on temp class that saw the not yet resolved class in the
4543 // class_table_ during EnsureResolved.
4544 klass->SetStatus(mirror::Class::kStatusRetired, self);
4545
4546 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4547 // This will notify waiters on new_class that saw the not yet resolved
4548 // class in the class_table_ during EnsureResolved.
4549 new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004550 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004551 return true;
4552}
4553
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004554bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004555 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004556 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4557 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004558 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004559 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004560 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004561 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004562 return false;
4563 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004564 // Verify
4565 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004566 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004567 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004568 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004569 return false;
4570 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004571 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004572 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004573 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004574 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004575 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004576 for (size_t i = 0; i < interfaces->Size(); i++) {
4577 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004578 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004579 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004580 DCHECK(Thread::Current()->IsExceptionPending());
4581 return false;
4582 }
4583 // Verify
4584 if (!klass->CanAccess(interface)) {
4585 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004586 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004587 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004588 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004589 return false;
4590 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004591 }
4592 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004593 // Mark the class as loaded.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004594 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004595 return true;
4596}
4597
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004598bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004599 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004600 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004601 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004602 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004603 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004604 return false;
4605 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004606 return true;
4607 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004608 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004609 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4610 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004611 return false;
4612 }
4613 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004614 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004615 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004616 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004617 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004618 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004619 return false;
4620 }
4621 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004622 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004623 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004624 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004625 return false;
4626 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004627
Brian Carlstromf3632832014-05-20 15:36:53 -07004628 // Inherit kAccClassIsFinalizable from the superclass in case this
4629 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004630 if (super->IsFinalizable()) {
4631 klass->SetFinalizable();
4632 }
4633
Elliott Hughes2da50362011-10-10 16:57:08 -07004634 // Inherit reference flags (if any) from the superclass.
4635 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4636 if (reference_flags != 0) {
4637 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4638 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004639 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004640 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004641 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004642 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004643 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004644 return false;
4645 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004646
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004647 if (kIsDebugBuild) {
4648 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004649 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004650 CHECK(super->IsResolved());
4651 super = super->GetSuperClass();
4652 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004653 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004654 return true;
4655}
4656
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004657// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004658bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004659 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4660 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004661 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004662 if (klass->IsInterface()) {
4663 // No vtable.
4664 size_t count = klass->NumVirtualMethods();
4665 if (!IsUint(16, count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004666 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004667 return false;
4668 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004669 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004670 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004671 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004672 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4673 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004674 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004675 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004676}
4677
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004678// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4679// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4680// caches in the implementation below.
4681class MethodNameAndSignatureComparator FINAL : public ValueObject {
4682 public:
4683 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4684 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4685 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4686 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004687 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4688 }
4689
4690 const char* GetName() {
4691 if (name_ == nullptr) {
4692 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4693 }
4694 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004695 }
4696
4697 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4698 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4699 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4700 const DexFile* other_dex_file = other->GetDexFile();
4701 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4702 if (dex_file_ == other_dex_file) {
4703 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4704 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004705 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004706 uint32_t other_name_len;
4707 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4708 &other_name_len);
4709 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4710 return false;
4711 }
4712 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4713 }
4714
4715 private:
4716 // Dex file for the method to compare against.
4717 const DexFile* const dex_file_;
4718 // MethodId for the method to compare against.
4719 const DexFile::MethodId* const mid_;
4720 // Lazily computed name from the dex file's strings.
4721 const char* name_;
4722 // Lazily computed name length.
4723 uint32_t name_len_;
4724};
4725
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004726class LinkVirtualHashTable {
4727 public:
4728 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4729 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4730 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4731 }
4732 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4733 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4734 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004735 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004736 uint32_t index = hash % hash_size_;
4737 // Linear probe until we have an empty slot.
4738 while (hash_table_[index] != invalid_index_) {
4739 if (++index == hash_size_) {
4740 index = 0;
4741 }
4742 }
4743 hash_table_[index] = virtual_method_index;
4744 }
4745 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4746 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4747 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004748 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004749 size_t index = hash % hash_size_;
4750 while (true) {
4751 const uint32_t value = hash_table_[index];
4752 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4753 // the block and can safely assume not found.
4754 if (value == invalid_index_) {
4755 break;
4756 }
4757 if (value != removed_index_) { // This signifies not already overriden.
4758 mirror::ArtMethod* virtual_method =
4759 klass_->GetVirtualMethodDuringLinking(value);
4760 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4761 hash_table_[index] = removed_index_;
4762 return value;
4763 }
4764 }
4765 if (++index == hash_size_) {
4766 index = 0;
4767 }
4768 }
4769 return GetNotFoundIndex();
4770 }
4771 static uint32_t GetNotFoundIndex() {
4772 return invalid_index_;
4773 }
4774
4775 private:
4776 static const uint32_t invalid_index_;
4777 static const uint32_t removed_index_;
4778
4779 Handle<mirror::Class> klass_;
4780 const size_t hash_size_;
4781 uint32_t* const hash_table_;
4782};
4783
4784const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4785const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4786
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004787bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004788 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004789 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004790 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4791 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004792 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004793 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004794 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004795 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4796 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4797 if (UNLIKELY(vtable.Get() == nullptr)) {
4798 CHECK(self->IsExceptionPending()); // OOME.
4799 return false;
4800 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004801 for (size_t i = 0; i < super_vtable_length; i++) {
4802 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004803 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004804 if (num_virtual_methods == 0) {
4805 klass->SetVTable(vtable.Get());
4806 return true;
4807 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004808 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004809 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4810 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4811 if (num_virtual_methods == 0) {
4812 klass->SetVTable(super_vtable);
4813 return true;
4814 }
4815 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004816 if (UNLIKELY(vtable.Get() == nullptr)) {
4817 CHECK(self->IsExceptionPending()); // OOME.
4818 return false;
4819 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004820 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004821 // How the algorithm works:
4822 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4823 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4824 // method which has not been matched to a vtable method, and j if the virtual method at the
4825 // index overrode the super virtual method at index j.
4826 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4827 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4828 // the need for the initial vtable which we later shrink back down).
4829 // 3. Add non overridden methods to the end of the vtable.
4830 static constexpr size_t kMaxStackHash = 250;
4831 const size_t hash_table_size = num_virtual_methods * 3;
4832 uint32_t* hash_table_ptr;
4833 std::unique_ptr<uint32_t[]> hash_heap_storage;
4834 if (hash_table_size <= kMaxStackHash) {
4835 hash_table_ptr = reinterpret_cast<uint32_t*>(
4836 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4837 } else {
4838 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4839 hash_table_ptr = hash_heap_storage.get();
4840 }
4841 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4842 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004843 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004844 hash_table.Add(i);
4845 }
4846 // Loop through each super vtable method and see if they are overriden by a method we added to
4847 // the hash table.
4848 for (size_t j = 0; j < super_vtable_length; ++j) {
4849 // Search the hash table to see if we are overidden by any method.
4850 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4851 MethodNameAndSignatureComparator super_method_name_comparator(
4852 super_method->GetInterfaceMethodIfProxy());
4853 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4854 if (hash_index != hash_table.GetNotFoundIndex()) {
4855 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4856 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4857 super_method->GetAccessFlags())) {
4858 if (super_method->IsFinal()) {
4859 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4860 PrettyMethod(virtual_method).c_str(),
4861 super_method->GetDeclaringClassDescriptor());
4862 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004863 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004864 vtable->SetWithoutChecks<false>(j, virtual_method);
4865 virtual_method->SetMethodIndex(j);
4866 } else {
4867 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004868 << " would have incorrectly overridden the package-private method in "
4869 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004870 }
4871 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004872 }
4873 // Add the non overridden methods at the end.
4874 size_t actual_count = super_vtable_length;
4875 for (size_t i = 0; i < num_virtual_methods; ++i) {
4876 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4877 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4878 if (method_idx < super_vtable_length &&
4879 local_method == vtable->GetWithoutChecks(method_idx)) {
4880 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004881 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004882 vtable->SetWithoutChecks<false>(actual_count, local_method);
4883 local_method->SetMethodIndex(actual_count);
4884 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004885 }
4886 if (!IsUint(16, actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004887 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004888 return false;
4889 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004890 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004891 CHECK_LE(actual_count, max_count);
4892 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004893 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004894 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004895 CHECK(self->IsExceptionPending()); // OOME.
4896 return false;
4897 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004898 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004899 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004900 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004901 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004902 if (!IsUint(16, num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004903 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4904 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004905 return false;
4906 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004907 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4908 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004909 CHECK(self->IsExceptionPending()); // OOME.
4910 return false;
4911 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004912 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004913 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004914 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004915 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004916 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004917 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004918 }
4919 return true;
4920}
4921
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004922bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4923 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4924 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004925 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004926 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004927 const bool has_superclass = klass->HasSuperClass();
4928 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4929 const bool have_interfaces = interfaces.Get() != nullptr;
4930 const size_t num_interfaces =
4931 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4932 if (num_interfaces == 0) {
4933 if (super_ifcount == 0) {
4934 // Class implements no interfaces.
4935 DCHECK_EQ(klass->GetIfTableCount(), 0);
4936 DCHECK(klass->GetIfTable() == nullptr);
4937 return true;
4938 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004939 // Class implements same interfaces as parent, are any of these not marker interfaces?
4940 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004941 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004942 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004943 if (super_iftable->GetMethodArrayCount(i) > 0) {
4944 has_non_marker_interface = true;
4945 break;
4946 }
4947 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004948 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004949 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004950 klass->SetIfTable(super_iftable);
4951 return true;
4952 }
4953 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004954 size_t ifcount = super_ifcount + num_interfaces;
4955 for (size_t i = 0; i < num_interfaces; i++) {
4956 mirror::Class* interface = have_interfaces ?
4957 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4958 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004959 if (UNLIKELY(!interface->IsInterface())) {
4960 std::string temp;
4961 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4962 PrettyDescriptor(klass.Get()).c_str(),
4963 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4964 return false;
4965 }
4966 ifcount += interface->GetIfTableCount();
4967 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004968 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004969 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004970 CHECK(self->IsExceptionPending()); // OOME.
4971 return false;
4972 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004973 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004974 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004975 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004976 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004977 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004978 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004979 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004980 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004981 // Flatten the interface inheritance hierarchy.
4982 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004983 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004984 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4985 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004986 // Check if interface is already in iftable
4987 bool duplicate = false;
4988 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004989 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004990 if (existing_interface == interface) {
4991 duplicate = true;
4992 break;
4993 }
4994 }
4995 if (!duplicate) {
4996 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004997 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004998 // Add this interface's non-duplicate super-interfaces.
4999 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005000 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005001 bool super_duplicate = false;
5002 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005003 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005004 if (existing_interface == super_interface) {
5005 super_duplicate = true;
5006 break;
5007 }
5008 }
5009 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07005010 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005011 }
5012 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005013 }
5014 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005015 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08005016 // Shrink iftable in case duplicates were found
5017 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005018 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005019 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005020 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005021 CHECK(self->IsExceptionPending()); // OOME.
5022 return false;
5023 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08005024 ifcount = idx;
5025 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005026 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08005027 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005028 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07005029 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07005030 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005031 return true;
5032 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005033 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005034 size_t max_miranda_methods = 0; // The max size of miranda_list.
5035 for (size_t i = 0; i < ifcount; ++i) {
5036 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
5037 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005038 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005039 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005040 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5041 hs.NewHandle(klass->GetVTableDuringLinking()));
5042 // Copy the IMT from the super class if possible.
5043 bool extend_super_iftable = false;
5044 if (has_superclass) {
5045 mirror::Class* super_class = klass->GetSuperClass();
5046 extend_super_iftable = true;
5047 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5048 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5049 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5050 }
5051 } else {
5052 // No imt in the super class, need to reconstruct from the iftable.
5053 mirror::IfTable* if_table = super_class->GetIfTable();
5054 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5055 const size_t length = super_class->GetIfTableCount();
5056 for (size_t i = 0; i < length; ++i) {
5057 mirror::Class* interface = iftable->GetInterface(i);
5058 const size_t num_virtuals = interface->NumVirtualMethods();
5059 const size_t method_array_count = if_table->GetMethodArrayCount(i);
5060 DCHECK_EQ(num_virtuals, method_array_count);
5061 if (method_array_count == 0) {
5062 continue;
5063 }
5064 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5065 for (size_t j = 0; j < num_virtuals; ++j) {
5066 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5067 if (method->IsMiranda()) {
5068 continue;
5069 }
5070 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5071 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5072 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5073 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5074 out_imt->SetReference(imt_index, method);
5075 } else if (imt_ref != conflict_method) {
5076 out_imt->SetReference(imt_index, conflict_method);
5077 }
5078 }
5079 }
5080 }
5081 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005082 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005083 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005084 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07005085 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005086 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005087 const bool is_super = i < super_ifcount;
5088 const bool super_interface = is_super && extend_super_iftable;
5089 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5090 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5091 if (super_interface) {
5092 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5093 DCHECK(if_table != nullptr);
5094 DCHECK(if_table->GetMethodArray(i) != nullptr);
5095 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005096 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005097 AsObjectArray<mirror::ArtMethod>());
5098 // We are overwriting a super class interface, try to only virtual methods instead of the
5099 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005100 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005101 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005102 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005103 // A new interface, we need the whole vtable incase a new interface method is implemented
5104 // in the whole superclass.
5105 input_array = vtable;
5106 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005107 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005108 CHECK(self->IsExceptionPending()); // OOME.
5109 return false;
5110 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005111 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005112 if (input_array.Get() == nullptr) {
5113 // If the added virtual methods is empty, do nothing.
5114 DCHECK(super_interface);
5115 continue;
5116 }
Ian Rogers62d6c772013-02-27 08:32:07 -08005117 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005118 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005119 MethodNameAndSignatureComparator interface_name_comparator(
5120 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07005121 int32_t k;
5122 // For each method listed in the interface's method list, find the
5123 // matching method in our class's method list. We want to favor the
5124 // subclass over the superclass, which just requires walking
5125 // back from the end of the vtable. (This only matters if the
5126 // superclass defines a private method and this class redefines
5127 // it -- otherwise it would use the same vtable slot. In .dex files
5128 // those don't end up in the virtual method table, so it shouldn't
5129 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005130 for (k = input_array->GetLength() - 1; k >= 0; --k) {
5131 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005132 mirror::ArtMethod* vtable_method_for_name_comparison =
5133 vtable_method->GetInterfaceMethodIfProxy();
5134 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005135 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005136 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005137 ThrowIllegalAccessError(
5138 klass.Get(),
5139 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005140 PrettyMethod(vtable_method).c_str(),
5141 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07005142 return false;
5143 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005144 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07005145 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005146 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5147 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5148 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5149 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5150 out_imt->SetReference(imt_index, vtable_method);
5151 } else if (imt_ref != conflict_method) {
5152 // If we are not a conflict and we have the same signature and name as the imt entry,
5153 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005154 MethodNameAndSignatureComparator imt_ref_name_comparator(
5155 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005156 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005157 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005158 out_imt->SetReference(imt_index, vtable_method);
5159 } else {
5160 out_imt->SetReference(imt_index, conflict_method);
5161 }
Jeff Hao88474b42013-10-23 16:24:40 -07005162 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005163 break;
5164 }
5165 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005166 if (k < 0 && !super_interface) {
5167 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005168 for (size_t l = 0; l < miranda_list_size; ++l) {
5169 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07005170 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005171 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07005172 break;
5173 }
5174 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005175 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005176 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005177 miranda_method = interface_method->Clone(self)->AsArtMethod();
5178 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005179 CHECK(self->IsExceptionPending()); // OOME.
5180 return false;
5181 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005182 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005183 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07005184 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005185 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005186 }
5187 }
5188 }
5189 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005190 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07005191 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005192 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07005193 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5194 if (old_method_count == 0) {
5195 virtuals = AllocArtMethodArray(self, new_method_count);
5196 } else {
5197 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5198 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005199 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005200 CHECK(self->IsExceptionPending()); // OOME.
5201 return false;
5202 }
5203 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005204
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005205 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005206 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005207 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005208 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07005209 CHECK(self->IsExceptionPending()); // OOME.
5210 return false;
5211 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07005212 for (size_t i = 0; i < miranda_list_size; ++i) {
5213 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07005214 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07005215 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5216 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5217 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005218 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005219 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005220 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005221 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005222 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005223
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005224 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08005225 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5226 for (int i = 0; i < check_vtable->GetLength(); ++i) {
5227 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07005228 }
Elliott Hughes4681c802011-09-25 18:04:37 -07005229 }
5230
Ian Rogers7b078e82014-09-10 14:44:24 -07005231 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005232 return true;
5233}
5234
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005235bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005236 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005237 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005238}
5239
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005240bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005241 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07005242 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07005243}
5244
Brian Carlstromdbc05252011-09-09 01:59:59 -07005245struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07005246 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5247 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005248 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Ian Rogersef7d42f2014-01-06 12:55:46 -08005249 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005250 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07005251 // 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 -07005252 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5253 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08005254 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00005255 if (type1 == Primitive::kPrimNot) {
5256 // Reference always goes first.
5257 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08005258 }
Vladimir Markod5777482014-11-12 17:02:02 +00005259 if (type2 == Primitive::kPrimNot) {
5260 // Reference always goes first.
5261 return false;
5262 }
5263 size_t size1 = Primitive::ComponentSize(type1);
5264 size_t size2 = Primitive::ComponentSize(type2);
5265 if (size1 != size2) {
5266 // Larger primitive types go first.
5267 return size1 > size2;
5268 }
5269 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5270 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005271 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005272 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5273 // by name and for equal names by type id index.
5274 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5275 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07005276 }
5277};
5278
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005279bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07005280 size_t* class_size) {
5281 self->AllowThreadSuspension();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005282 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005283 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005284
Brian Carlstromea46f952013-07-30 01:26:50 -07005285 mirror::ObjectArray<mirror::ArtField>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005286 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005287
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005288 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07005289 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005290 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00005291 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005292 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005293 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005294 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07005295 CHECK(super_class->IsResolved())
5296 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005297 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005298 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005299 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005300
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005301 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005302
Brian Carlstromdbc05252011-09-09 01:59:59 -07005303 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07005304 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromea46f952013-07-30 01:26:50 -07005305 std::deque<mirror::ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07005306 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07005307 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07005308 for (size_t i = 0; i < num_fields; i++) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005309 mirror::ArtField* f = fields->Get(i);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005310 CHECK(f != nullptr) << PrettyClass(klass.Get());
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005311 grouped_and_sorted_fields.push_back(f);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005312 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07005313 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5314 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07005315
Fred Shih381e4ca2014-08-25 17:24:27 -07005316 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07005317 size_t current_field = 0;
5318 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07005319 FieldGaps gaps;
5320
Brian Carlstromdbc05252011-09-09 01:59:59 -07005321 for (; current_field < num_fields; current_field++) {
Brian Carlstromea46f952013-07-30 01:26:50 -07005322 mirror::ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005323 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07005324 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07005325 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07005326 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005327 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005328 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5329 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07005330 MemberOffset old_offset = field_offset;
5331 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5332 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5333 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005334 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07005335 grouped_and_sorted_fields.pop_front();
5336 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005337 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00005338 field_offset = MemberOffset(field_offset.Uint32Value() +
5339 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005340 }
Fred Shih381e4ca2014-08-25 17:24:27 -07005341 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5342 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00005343 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5344 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5345 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5346 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07005347 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5348 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07005349 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005350
Elliott Hughesadb460d2011-10-05 17:02:34 -07005351 // 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 -07005352 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07005353 // We know there are no non-reference fields in the Reference classes, and we know
5354 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07005355 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07005356 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07005357 --num_reference_fields;
5358 }
5359
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005360 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005361 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005362 if (is_static) {
5363 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005364 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07005365 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005366 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07005367 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08005368 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
5369 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
5370 } else {
5371 std::string temp;
5372 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5373 size_t previous_size = klass->GetObjectSize();
5374 if (previous_size != 0) {
5375 // Make sure that we didn't originally have an incorrect size.
5376 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5377 }
5378 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07005379 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005380 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005381 }
Vladimir Marko76649e82014-11-10 18:32:59 +00005382
5383 if (kIsDebugBuild) {
5384 // Make sure that the fields array is ordered by name but all reference
5385 // offsets are at the beginning as far as alignment allows.
5386 MemberOffset start_ref_offset = is_static
5387 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5388 : klass->GetFirstReferenceInstanceFieldOffset();
5389 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5390 num_reference_fields *
5391 sizeof(mirror::HeapReference<mirror::Object>));
5392 MemberOffset current_ref_offset = start_ref_offset;
5393 for (size_t i = 0; i < num_fields; i++) {
5394 mirror::ArtField* field = fields->Get(i);
5395 if ((false)) { // enable to debug field layout
5396 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5397 << " class=" << PrettyClass(klass.Get())
5398 << " field=" << PrettyField(field)
5399 << " offset="
5400 << field->GetField32(mirror::ArtField::OffsetOffset());
5401 }
5402 if (i != 0) {
5403 mirror::ArtField* prev_field = fields->Get(i - 1u);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00005404 // NOTE: The field names can be the same. This is not possible in the Java language
5405 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5406 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00005407 }
5408 Primitive::Type type = field->GetTypeAsPrimitiveType();
5409 bool is_primitive = type != Primitive::kPrimNot;
5410 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5411 strcmp("referent", field->GetName()) == 0) {
5412 is_primitive = true; // We lied above, so we have to expect a lie here.
5413 }
5414 MemberOffset offset = field->GetOffsetDuringLinking();
5415 if (is_primitive) {
5416 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5417 // Shuffled before references.
5418 size_t type_size = Primitive::ComponentSize(type);
5419 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5420 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5421 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5422 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5423 }
5424 } else {
5425 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5426 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5427 sizeof(mirror::HeapReference<mirror::Object>));
5428 }
5429 }
5430 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5431 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005432 return true;
5433}
5434
Vladimir Marko76649e82014-11-10 18:32:59 +00005435// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005436void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005437 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005438 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005439 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005440 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005441 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005442 // Compute reference offsets unless our superclass overflowed.
5443 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5444 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005445 if (num_reference_fields != 0u) {
5446 // All of the fields that contain object references are guaranteed be grouped in memory
5447 // starting at an appropriately aligned address after super class object data.
5448 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5449 sizeof(mirror::HeapReference<mirror::Object>));
5450 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005451 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005452 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005453 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005454 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005455 reference_offsets |= (0xffffffffu << start_bit) &
5456 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005457 }
5458 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005459 }
5460 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005461 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005462}
5463
Mathieu Chartier590fee92013-09-13 13:46:47 -07005464mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005465 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005466 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005467 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005468 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005469 return resolved;
5470 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005471 uint32_t utf16_length;
5472 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005473 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005474 dex_cache->SetResolvedString(string_idx, string);
5475 return string;
5476}
5477
Mathieu Chartier590fee92013-09-13 13:46:47 -07005478mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005479 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005480 StackHandleScope<2> hs(Thread::Current());
5481 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5482 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005483 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5484}
5485
5486mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005487 Handle<mirror::DexCache> dex_cache,
5488 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005489 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005490 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005491 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005492 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005493 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005494 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005495 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005496 // TODO: we used to throw here if resolved's class loader was not the
5497 // boot class loader. This was to permit different classes with the
5498 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005499 dex_cache->SetResolvedType(type_idx, resolved);
5500 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005501 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005502 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005503 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005504 StackHandleScope<1> hs(self);
5505 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
Ian Rogers62d6c772013-02-27 08:32:07 -08005506 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005507 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005508 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005509 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005510 self->GetException(nullptr)->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005511 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005512 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005513 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005514 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005515 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005516 return resolved;
5517}
5518
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005519mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005520 Handle<mirror::DexCache> dex_cache,
5521 Handle<mirror::ClassLoader> class_loader,
5522 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005523 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005524 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005525 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005526 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005527 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005528 return resolved;
5529 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005530 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005531 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005532 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005533 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005534 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005535 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005536 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005537 // Scan using method_idx, this saves string compares but will only hit for matching dex
5538 // caches/files.
5539 switch (type) {
5540 case kDirect: // Fall-through.
5541 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005542 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005543 break;
5544 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005545 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005546 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005547 break;
5548 case kSuper: // Fall-through.
5549 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005550 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005551 break;
5552 default:
5553 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005554 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005555 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005556 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005557 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005558 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005559 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005560 switch (type) {
5561 case kDirect: // Fall-through.
5562 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005563 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005564 break;
5565 case kInterface:
5566 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005567 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005568 break;
5569 case kSuper: // Fall-through.
5570 case kVirtual:
5571 resolved = klass->FindVirtualMethod(name, signature);
5572 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005573 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005574 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005575 // If we found a method, check for incompatible class changes.
5576 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005577 // Be a good citizen and update the dex cache to speed subsequent calls.
5578 dex_cache->SetResolvedMethod(method_idx, resolved);
5579 return resolved;
5580 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005581 // If we had a method, it's an incompatible-class-change error.
5582 if (resolved != nullptr) {
5583 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5584 } else {
5585 // We failed to find the method which means either an access error, an incompatible class
5586 // change, or no such method. First try to find the method among direct and virtual methods.
5587 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5588 const Signature signature = dex_file.GetMethodSignature(method_id);
5589 switch (type) {
5590 case kDirect:
5591 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005592 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005593 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5594 // have had a resolved method before, which triggers the "true" branch above.
5595 break;
5596 case kInterface:
5597 case kVirtual:
5598 case kSuper:
5599 resolved = klass->FindDirectMethod(name, signature);
5600 break;
5601 }
5602
5603 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005604 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005605 if (resolved != nullptr && referrer.Get() != nullptr) {
5606 mirror::Class* methods_class = resolved->GetDeclaringClass();
5607 mirror::Class* referring_class = referrer->GetDeclaringClass();
5608 if (!referring_class->CanAccess(methods_class)) {
5609 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5610 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005611 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005612 } else if (!referring_class->CanAccessMember(methods_class,
5613 resolved->GetAccessFlags())) {
5614 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005615 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005616 }
5617 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005618 if (!exception_generated) {
5619 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5620 // interface methods and throw if we find the method there. If we find nothing, throw a
5621 // NoSuchMethodError.
5622 switch (type) {
5623 case kDirect:
5624 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005625 if (resolved != nullptr) {
5626 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5627 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005628 resolved = klass->FindInterfaceMethod(name, signature);
5629 if (resolved != nullptr) {
5630 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5631 } else {
5632 ThrowNoSuchMethodError(type, klass, name, signature);
5633 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005634 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005635 break;
5636 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005637 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005638 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5639 } else {
5640 resolved = klass->FindVirtualMethod(name, signature);
5641 if (resolved != nullptr) {
5642 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5643 } else {
5644 ThrowNoSuchMethodError(type, klass, name, signature);
5645 }
5646 }
5647 break;
5648 case kSuper:
5649 if (resolved != nullptr) {
5650 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005651 } else {
5652 ThrowNoSuchMethodError(type, klass, name, signature);
5653 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005654 break;
5655 case kVirtual:
5656 if (resolved != nullptr) {
5657 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5658 } else {
5659 resolved = klass->FindInterfaceMethod(name, signature);
5660 if (resolved != nullptr) {
5661 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5662 } else {
5663 ThrowNoSuchMethodError(type, klass, name, signature);
5664 }
5665 }
5666 break;
5667 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005668 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005669 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005670 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005671 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005672 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005673}
5674
Mathieu Chartier590fee92013-09-13 13:46:47 -07005675mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005676 Handle<mirror::DexCache> dex_cache,
5677 Handle<mirror::ClassLoader> class_loader,
Brian Carlstrome8104522013-10-15 21:56:36 -07005678 bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005679 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005680 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005681 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005682 return resolved;
5683 }
5684 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005685 Thread* const self = Thread::Current();
5686 StackHandleScope<1> hs(self);
5687 Handle<mirror::Class> klass(
5688 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005689 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005690 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005691 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005692 }
5693
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005694 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005695 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005696 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005697 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005698 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005699
Andreas Gampe58a5af82014-07-31 16:23:49 -07005700 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005701 const char* name = dex_file.GetFieldName(field_id);
5702 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5703 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005704 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005705 } else {
5706 resolved = klass->FindInstanceField(name, type);
5707 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005708 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005709 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005710 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005711 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005712 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005713 dex_cache->SetResolvedField(field_idx, resolved);
Ian Rogersb067ac22011-12-13 18:05:09 -08005714 return resolved;
5715}
5716
Brian Carlstromea46f952013-07-30 01:26:50 -07005717mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005718 uint32_t field_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005719 Handle<mirror::DexCache> dex_cache,
5720 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005721 DCHECK(dex_cache.Get() != nullptr);
Brian Carlstromea46f952013-07-30 01:26:50 -07005722 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005723 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005724 return resolved;
5725 }
5726 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005727 Thread* self = Thread::Current();
5728 StackHandleScope<1> hs(self);
5729 Handle<mirror::Class> klass(
5730 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005731 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005732 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005733 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005734 }
5735
Ian Rogersdfb325e2013-10-30 01:00:44 -07005736 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5737 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005738 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005739 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005740 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005741 dex_cache->SetResolvedField(field_idx, resolved);
5742 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005743 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005744 }
5745 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005746}
5747
Brian Carlstromea46f952013-07-30 01:26:50 -07005748const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005749 uint32_t* length) {
5750 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5751 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005752 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005753 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005754 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005755}
5756
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005757void ClassLinker::DumpAllClasses(int flags) {
5758 if (dex_cache_image_class_lookup_required_) {
5759 MoveImageClassesToClassTable();
5760 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005761 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5762 // 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 -08005763 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005764 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005765 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005766 for (GcRoot<mirror::Class>& it : class_table_) {
5767 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005768 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005769 }
5770
5771 for (size_t i = 0; i < all_classes.size(); ++i) {
5772 all_classes[i]->DumpClass(std::cerr, flags);
5773 }
5774}
5775
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005776static OatFile::OatMethod CreateOatMethod(const void* code, bool is_portable) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005777 CHECK_EQ(kUsePortableCompiler, is_portable);
5778 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005779 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5780 base -= sizeof(void*); // Move backward so that code_offset != 0.
5781 const uint32_t code_offset = sizeof(void*);
5782 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005783}
5784
5785bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5786 return (entry_point == GetPortableResolutionStub()) ||
5787 (portable_resolution_trampoline_ == entry_point);
5788}
5789
5790bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5791 return (entry_point == GetQuickResolutionStub()) ||
5792 (quick_resolution_trampoline_ == entry_point);
5793}
5794
5795bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5796 return (entry_point == GetPortableToInterpreterBridge());
5797 // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5798}
5799
5800bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5801 return (entry_point == GetQuickToInterpreterBridge()) ||
5802 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5803}
5804
5805bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5806 return (entry_point == GetQuickGenericJniStub()) ||
5807 (quick_generic_jni_trampoline_ == entry_point);
5808}
5809
5810const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5811 return GetQuickGenericJniStub();
5812}
5813
5814void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5815 bool is_portable) const {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005816 OatFile::OatMethod oat_method = CreateOatMethod(method_code, is_portable);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005817 oat_method.LinkMethod(method);
5818 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5819 // Create bridges to transition between different kinds of compiled bridge.
5820 if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5821 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5822 } else {
5823 CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5824 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5825 method->SetIsPortableCompiled();
5826 }
5827}
5828
5829void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5830 if (!method->IsNative()) {
5831 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5832 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5833 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5834 } else {
5835 const void* quick_method_code = GetQuickGenericJniStub();
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005836 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, false);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005837 oat_method.LinkMethod(method);
5838 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5839 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5840 }
5841}
5842
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005843void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005844 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005845 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005846 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005847 MoveImageClassesToClassTable();
5848 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005849 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005850 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5851 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005852}
5853
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005854size_t ClassLinker::NumLoadedClasses() {
5855 if (dex_cache_image_class_lookup_required_) {
5856 MoveImageClassesToClassTable();
5857 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005858 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005859 // Only return non zygote classes since these are the ones which apps which care about.
5860 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005861}
5862
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005863pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005864 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005865}
5866
5867pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005868 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005869}
5870
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005871void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005872 DCHECK(!init_done_);
5873
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005874 DCHECK(klass != nullptr);
5875 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005876
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005877 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005878 DCHECK(class_roots != nullptr);
5879 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005880 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005881}
5882
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005883const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5884 static const char* class_roots_descriptors[] = {
5885 "Ljava/lang/Class;",
5886 "Ljava/lang/Object;",
5887 "[Ljava/lang/Class;",
5888 "[Ljava/lang/Object;",
5889 "Ljava/lang/String;",
5890 "Ljava/lang/DexCache;",
5891 "Ljava/lang/ref/Reference;",
5892 "Ljava/lang/reflect/ArtField;",
5893 "Ljava/lang/reflect/ArtMethod;",
5894 "Ljava/lang/reflect/Proxy;",
5895 "[Ljava/lang/String;",
5896 "[Ljava/lang/reflect/ArtField;",
5897 "[Ljava/lang/reflect/ArtMethod;",
5898 "Ljava/lang/ClassLoader;",
5899 "Ljava/lang/Throwable;",
5900 "Ljava/lang/ClassNotFoundException;",
5901 "Ljava/lang/StackTraceElement;",
5902 "Z",
5903 "B",
5904 "C",
5905 "D",
5906 "F",
5907 "I",
5908 "J",
5909 "S",
5910 "V",
5911 "[Z",
5912 "[B",
5913 "[C",
5914 "[D",
5915 "[F",
5916 "[I",
5917 "[J",
5918 "[S",
5919 "[Ljava/lang/StackTraceElement;",
5920 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005921 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5922 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005923
5924 const char* descriptor = class_roots_descriptors[class_root];
5925 CHECK(descriptor != nullptr);
5926 return descriptor;
5927}
5928
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005929std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5930 const {
5931 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005932 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005933}
5934
5935bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5936 const GcRoot<mirror::Class>& b) {
5937 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5938 return false;
5939 }
5940 std::string temp;
5941 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5942}
5943
5944std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5945 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005946 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005947}
5948
5949bool ClassLinker::ClassDescriptorHashEquals::operator()(
5950 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5951 if (a.Read()->GetClassLoader() != b.second) {
5952 return false;
5953 }
5954 return a.Read()->DescriptorEquals(b.first);
5955}
5956
5957bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5958 const char* descriptor) {
5959 return a.Read()->DescriptorEquals(descriptor);
5960}
5961
5962std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005963 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005964}
5965
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005966} // namespace art