class_linker.cc revision 564ff985184737977aa26c485d0c1a413e530705
15d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)/* 25d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * Copyright (C) 2011 The Android Open Source Project 35d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * 45d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * Licensed under the Apache License, Version 2.0 (the "License"); 55d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * you may not use this file except in compliance with the License. 65d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * You may obtain a copy of the License at 75d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * 85d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * http://www.apache.org/licenses/LICENSE-2.0 95d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * 1023730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles) * Unless required by applicable law or agreed to in writing, software 115d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * distributed under the License is distributed on an "AS IS" BASIS, 12010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 135d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * See the License for the specific language governing permissions and 145d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) * limitations under the License. 15e5d81f57cb97b3b6b7fccc9c5610d21eb81db09dBen Murdoch */ 16a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) 175d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "class_linker.h" 185d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 195d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <fcntl.h> 205d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <sys/file.h> 215d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <sys/stat.h> 225d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <deque> 235d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <memory> 245d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <string> 255d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <utility> 265d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <vector> 275d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 285d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "base/casts.h" 295d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "base/logging.h" 305d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "base/scoped_flock.h" 315d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "base/stl_util.h" 325d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "base/unix_file/fd_file.h" 335d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "class_linker-inl.h" 345d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "compiler_callbacks.h" 355d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "debugger.h" 365d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "dex_file-inl.h" 375d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "gc_root-inl.h" 385d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "gc/accounting/card_table-inl.h" 395d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "gc/accounting/heap_bitmap.h" 40f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "gc/heap.h" 410de6073388f4e2780db8536178b129cd8f6ab386Torne (Richard Coles)#include "gc/space/image_space.h" 425d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "handle_scope.h" 435d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "intern_table.h" 445d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "interpreter/interpreter.h" 455d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "leb128.h" 465d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "method_helper-inl.h" 475d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "oat.h" 485d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "oat_file.h" 4923730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)#include "object_lock.h" 5023730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)#include "mirror/art_field-inl.h" 515d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "mirror/art_method-inl.h" 52effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch#include "mirror/class.h" 53effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch#include "mirror/class-inl.h" 545d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "mirror/class_loader.h" 555d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "mirror/dex_cache-inl.h" 565d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "mirror/iftable-inl.h" 575d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "mirror/object-inl.h" 585d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "mirror/object_array-inl.h" 595d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "mirror/proxy.h" 605d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "mirror/reference-inl.h" 61010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "mirror/stack_trace_element.h" 625d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "mirror/string-inl.h" 635d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "os.h" 645d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "runtime.h" 65116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch#include "entrypoints/entrypoint_utils.h" 66116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch#include "ScopedLocalRef.h" 675d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "scoped_thread_state_change.h" 685d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "handle_scope-inl.h" 695d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "thread.h" 705d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "utils.h" 715d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "verifier/method_verifier.h" 725d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "well_known_classes.h" 735d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 745d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)namespace art { 755d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 765d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)static void ThrowNoClassDefFoundError(const char* fmt, ...) 775d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) __attribute__((__format__(__printf__, 1, 2))) 785d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 79116680a4aac90f2aa7413d9095a592090648e557Ben Murdochstatic void ThrowNoClassDefFoundError(const char* fmt, ...) { 80116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch va_list args; 815d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) va_start(args, fmt); 8223730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles) Thread* self = Thread::Current(); 8323730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles) ThrowLocation throw_location = self->GetCurrentLocationForThrow(); 84116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args); 855d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) va_end(args); 865d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)} 870de6073388f4e2780db8536178b129cd8f6ab386Torne (Richard Coles) 885d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)static void ThrowEarlierClassFailure(mirror::Class* c) 895d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 905d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) // The class failed to initialize on a previous attempt, so we want to throw 915d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we 92c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch // failed in verification, in which case v2 5.4.1 says we need to re-throw 935d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) // the previous error. 945d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) if (!Runtime::Current()->IsCompiler()) { // Give info if this occurs at runtime. 950de6073388f4e2780db8536178b129cd8f6ab386Torne (Richard Coles) LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c); 96116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch } 975d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 985d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus(); 99c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch Thread* self = Thread::Current(); 100c5cede9ae108bb15f6b7a8aea21c7e1fefa2834cBen Murdoch ThrowLocation throw_location = self->GetCurrentLocationForThrow(); 1015d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) if (c->GetVerifyErrorClass() != nullptr) { 1025d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) // TODO: change the verifier to store an _instance_, with a useful detail message? 1035d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) std::string temp; 104f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp), 1055d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) PrettyDescriptor(c).c_str()); 1065d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) } else { 1075d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;", 1085d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) PrettyDescriptor(c).c_str()); 1095d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) } 1105d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)} 111 112static void WrapExceptionInInitializer() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 113 Thread* self = Thread::Current(); 114 JNIEnv* env = self->GetJniEnv(); 115 116 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred()); 117 CHECK(cause.get() != nullptr); 118 119 env->ExceptionClear(); 120 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error); 121 env->Throw(cause.get()); 122 123 // We only wrap non-Error exceptions; an Error can just be used as-is. 124 if (!is_error) { 125 ThrowLocation throw_location = self->GetCurrentLocationForThrow(); 126 self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;", 127 nullptr); 128 } 129} 130 131const char* ClassLinker::class_roots_descriptors_[] = { 132 "Ljava/lang/Class;", 133 "Ljava/lang/Object;", 134 "[Ljava/lang/Class;", 135 "[Ljava/lang/Object;", 136 "Ljava/lang/String;", 137 "Ljava/lang/DexCache;", 138 "Ljava/lang/ref/Reference;", 139 "Ljava/lang/reflect/ArtField;", 140 "Ljava/lang/reflect/ArtMethod;", 141 "Ljava/lang/reflect/Proxy;", 142 "[Ljava/lang/String;", 143 "[Ljava/lang/reflect/ArtField;", 144 "[Ljava/lang/reflect/ArtMethod;", 145 "Ljava/lang/ClassLoader;", 146 "Ljava/lang/Throwable;", 147 "Ljava/lang/ClassNotFoundException;", 148 "Ljava/lang/StackTraceElement;", 149 "Z", 150 "B", 151 "C", 152 "D", 153 "F", 154 "I", 155 "J", 156 "S", 157 "V", 158 "[Z", 159 "[B", 160 "[C", 161 "[D", 162 "[F", 163 "[I", 164 "[J", 165 "[S", 166 "[Ljava/lang/StackTraceElement;", 167}; 168 169ClassLinker::ClassLinker(InternTable* intern_table) 170 // dex_lock_ is recursive as it may be used in stack dumping. 171 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel), 172 dex_cache_image_class_lookup_required_(false), 173 failed_dex_cache_class_lookups_(0), 174 class_roots_(nullptr), 175 array_iftable_(nullptr), 176 find_array_class_cache_next_victim_(0), 177 init_done_(false), 178 log_new_dex_caches_roots_(false), 179 log_new_class_table_roots_(false), 180 intern_table_(intern_table), 181 portable_resolution_trampoline_(nullptr), 182 quick_resolution_trampoline_(nullptr), 183 portable_imt_conflict_trampoline_(nullptr), 184 quick_imt_conflict_trampoline_(nullptr), 185 quick_generic_jni_trampoline_(nullptr), 186 quick_to_interpreter_bridge_trampoline_(nullptr) { 187 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax)); 188 memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*)); 189} 190 191// To set a value for generic JNI. May be necessary in compiler tests. 192extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*); 193extern "C" void art_quick_resolution_trampoline(mirror::ArtMethod*); 194extern "C" void art_quick_imt_conflict_trampoline(mirror::ArtMethod*); 195extern "C" void art_quick_to_interpreter_bridge(mirror::ArtMethod*); 196 197void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) { 198 VLOG(startup) << "ClassLinker::Init"; 199 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it."; 200 201 CHECK(!init_done_); 202 203 // java_lang_Class comes first, it's needed for AllocClass 204 Thread* self = Thread::Current(); 205 gc::Heap* heap = Runtime::Current()->GetHeap(); 206 // The GC can't handle an object with a null class since we can't get the size of this object. 207 heap->IncrementDisableMovingGC(self); 208 StackHandleScope<64> hs(self); // 64 is picked arbitrarily. 209 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>( 210 heap->AllocNonMovableObject<true>(self, nullptr, 211 mirror::Class::ClassClassSize(), 212 VoidFunctor())))); 213 CHECK(java_lang_Class.Get() != nullptr); 214 mirror::Class::SetClassClass(java_lang_Class.Get()); 215 java_lang_Class->SetClass(java_lang_Class.Get()); 216 if (kUseBakerOrBrooksReadBarrier) { 217 java_lang_Class->AssertReadBarrierPointer(); 218 } 219 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize()); 220 heap->DecrementDisableMovingGC(self); 221 // AllocClass(mirror::Class*) can now be used 222 223 // Class[] is used for reflection support. 224 Handle<mirror::Class> class_array_class(hs.NewHandle( 225 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize()))); 226 class_array_class->SetComponentType(java_lang_Class.Get()); 227 228 // java_lang_Object comes next so that object_array_class can be created. 229 Handle<mirror::Class> java_lang_Object(hs.NewHandle( 230 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize()))); 231 CHECK(java_lang_Object.Get() != nullptr); 232 // backfill Object as the super class of Class. 233 java_lang_Class->SetSuperClass(java_lang_Object.Get()); 234 java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self); 235 236 // Object[] next to hold class roots. 237 Handle<mirror::Class> object_array_class(hs.NewHandle( 238 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize()))); 239 object_array_class->SetComponentType(java_lang_Object.Get()); 240 241 // Setup the char (primitive) class to be used for char[]. 242 Handle<mirror::Class> char_class(hs.NewHandle( 243 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize()))); 244 245 // Setup the char[] class to be used for String. 246 Handle<mirror::Class> char_array_class(hs.NewHandle( 247 AllocClass(self, java_lang_Class.Get(), 248 mirror::Array::ClassSize()))); 249 char_array_class->SetComponentType(char_class.Get()); 250 mirror::CharArray::SetArrayClass(char_array_class.Get()); 251 252 // Setup String. 253 Handle<mirror::Class> java_lang_String(hs.NewHandle( 254 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize()))); 255 mirror::String::SetClass(java_lang_String.Get()); 256 java_lang_String->SetObjectSize(mirror::String::InstanceSize()); 257 java_lang_String->SetStatus(mirror::Class::kStatusResolved, self); 258 259 // Setup Reference. 260 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle( 261 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize()))); 262 mirror::Reference::SetClass(java_lang_ref_Reference.Get()); 263 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize()); 264 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self); 265 266 // Create storage for root classes, save away our work so far (requires descriptors). 267 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >( 268 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(), 269 kClassRootsMax)); 270 CHECK(!class_roots_.IsNull()); 271 SetClassRoot(kJavaLangClass, java_lang_Class.Get()); 272 SetClassRoot(kJavaLangObject, java_lang_Object.Get()); 273 SetClassRoot(kClassArrayClass, class_array_class.Get()); 274 SetClassRoot(kObjectArrayClass, object_array_class.Get()); 275 SetClassRoot(kCharArrayClass, char_array_class.Get()); 276 SetClassRoot(kJavaLangString, java_lang_String.Get()); 277 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get()); 278 279 // Setup the primitive type classes. 280 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean)); 281 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte)); 282 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort)); 283 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt)); 284 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong)); 285 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat)); 286 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble)); 287 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid)); 288 289 // Create array interface entries to populate once we can load system classes. 290 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2)); 291 292 // Create int array type for AllocDexCache (done in AppendToBootClassPath). 293 Handle<mirror::Class> int_array_class(hs.NewHandle( 294 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize()))); 295 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt)); 296 mirror::IntArray::SetArrayClass(int_array_class.Get()); 297 SetClassRoot(kIntArrayClass, int_array_class.Get()); 298 299 // now that these are registered, we can use AllocClass() and AllocObjectArray 300 301 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache. 302 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle( 303 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize()))); 304 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get()); 305 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize()); 306 java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self); 307 308 // Constructor, Field, Method, and AbstractMethod are necessary so 309 // that FindClass can link members. 310 Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle( 311 AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize()))); 312 CHECK(java_lang_reflect_ArtField.Get() != nullptr); 313 java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize()); 314 SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get()); 315 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self); 316 mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get()); 317 318 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle( 319 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize()))); 320 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr); 321 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize()); 322 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get()); 323 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self); 324 325 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get()); 326 327 // Set up array classes for string, field, method 328 Handle<mirror::Class> object_array_string(hs.NewHandle( 329 AllocClass(self, java_lang_Class.Get(), 330 mirror::ObjectArray<mirror::String>::ClassSize()))); 331 object_array_string->SetComponentType(java_lang_String.Get()); 332 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get()); 333 334 Handle<mirror::Class> object_array_art_method(hs.NewHandle( 335 AllocClass(self, java_lang_Class.Get(), 336 mirror::ObjectArray<mirror::ArtMethod>::ClassSize()))); 337 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get()); 338 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get()); 339 340 Handle<mirror::Class> object_array_art_field(hs.NewHandle( 341 AllocClass(self, java_lang_Class.Get(), 342 mirror::ObjectArray<mirror::ArtField>::ClassSize()))); 343 object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get()); 344 SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get()); 345 346 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create 347 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses 348 // these roots. 349 CHECK_NE(0U, boot_class_path.size()); 350 for (size_t i = 0; i != boot_class_path.size(); ++i) { 351 const DexFile* dex_file = boot_class_path[i]; 352 CHECK(dex_file != nullptr); 353 AppendToBootClassPath(*dex_file); 354 } 355 356 // now we can use FindSystemClass 357 358 // run char class through InitializePrimitiveClass to finish init 359 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar); 360 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor 361 362 // Create runtime resolution and imt conflict methods. Also setup the default imt. 363 Runtime* runtime = Runtime::Current(); 364 runtime->SetResolutionMethod(runtime->CreateResolutionMethod()); 365 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod()); 366 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod()); 367 runtime->SetDefaultImt(runtime->CreateDefaultImt(this)); 368 369 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that 370 // we do not need friend classes or a publicly exposed setter. 371 quick_generic_jni_trampoline_ = reinterpret_cast<void*>(art_quick_generic_jni_trampoline); 372 if (!runtime->IsCompiler()) { 373 // We need to set up the generic trampolines since we don't have an image. 374 quick_resolution_trampoline_ = reinterpret_cast<void*>(art_quick_resolution_trampoline); 375 quick_imt_conflict_trampoline_ = reinterpret_cast<void*>(art_quick_imt_conflict_trampoline); 376 quick_to_interpreter_bridge_trampoline_ = reinterpret_cast<void*>(art_quick_to_interpreter_bridge); 377 } 378 379 // Object, String and DexCache need to be rerun through FindSystemClass to finish init 380 java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self); 381 mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;"); 382 CHECK_EQ(java_lang_Object.Get(), Object_class); 383 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize()); 384 java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self); 385 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;"); 386 std::ostringstream os1, os2; 387 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail); 388 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail); 389 CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str(); 390 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize()); 391 java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self); 392 mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;"); 393 CHECK_EQ(java_lang_String.Get(), String_class); 394 CHECK_EQ(java_lang_DexCache.Get(), DexCache_class); 395 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize()); 396 397 // Setup the primitive array type classes - can't be done until Object has a vtable. 398 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z")); 399 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass)); 400 401 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B")); 402 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass)); 403 404 mirror::Class* found_char_array_class = FindSystemClass(self, "[C"); 405 CHECK_EQ(char_array_class.Get(), found_char_array_class); 406 407 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S")); 408 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass)); 409 410 mirror::Class* found_int_array_class = FindSystemClass(self, "[I"); 411 CHECK_EQ(int_array_class.Get(), found_int_array_class); 412 413 SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J")); 414 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass)); 415 416 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F")); 417 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass)); 418 419 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D")); 420 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass)); 421 422 mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;"); 423 CHECK_EQ(class_array_class.Get(), found_class_array_class); 424 425 mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;"); 426 CHECK_EQ(object_array_class.Get(), found_object_array_class); 427 428 // Setup the single, global copy of "iftable". 429 mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;"); 430 CHECK(java_lang_Cloneable != nullptr); 431 mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;"); 432 CHECK(java_io_Serializable != nullptr); 433 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to 434 // crawl up and explicitly list all of the supers as well. 435 { 436 mirror::IfTable* array_iftable = array_iftable_.Read(); 437 array_iftable->SetInterface(0, java_lang_Cloneable); 438 array_iftable->SetInterface(1, java_io_Serializable); 439 } 440 441 // Sanity check Class[] and Object[]'s interfaces. 442 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0)); 443 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1)); 444 CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0)); 445 CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1)); 446 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their 447 // dex_cache_ fields and register them in class_table_. 448 mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;"); 449 CHECK_EQ(java_lang_Class.Get(), Class_class); 450 451 java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self); 452 mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;"); 453 CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class); 454 455 java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self); 456 mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;"); 457 CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class); 458 459 mirror::Class* String_array_class = 460 FindSystemClass(self, class_roots_descriptors_[kJavaLangStringArrayClass]); 461 CHECK_EQ(object_array_string.Get(), String_array_class); 462 463 mirror::Class* Art_method_array_class = 464 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]); 465 CHECK_EQ(object_array_art_method.Get(), Art_method_array_class); 466 467 mirror::Class* Art_field_array_class = 468 FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]); 469 CHECK_EQ(object_array_art_field.Get(), Art_field_array_class); 470 471 // End of special init trickery, subsequent classes may be loaded via FindSystemClass. 472 473 // Create java.lang.reflect.Proxy root. 474 mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;"); 475 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy); 476 477 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes 478 // finish initializing Reference class 479 java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self); 480 mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;"); 481 CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class); 482 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize()); 483 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize()); 484 mirror::Class* java_lang_ref_FinalizerReference = 485 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"); 486 java_lang_ref_FinalizerReference->SetAccessFlags( 487 java_lang_ref_FinalizerReference->GetAccessFlags() | 488 kAccClassIsReference | kAccClassIsFinalizerReference); 489 mirror::Class* java_lang_ref_PhantomReference = 490 FindSystemClass(self, "Ljava/lang/ref/PhantomReference;"); 491 java_lang_ref_PhantomReference->SetAccessFlags( 492 java_lang_ref_PhantomReference->GetAccessFlags() | 493 kAccClassIsReference | kAccClassIsPhantomReference); 494 mirror::Class* java_lang_ref_SoftReference = 495 FindSystemClass(self, "Ljava/lang/ref/SoftReference;"); 496 java_lang_ref_SoftReference->SetAccessFlags( 497 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference); 498 mirror::Class* java_lang_ref_WeakReference = 499 FindSystemClass(self, "Ljava/lang/ref/WeakReference;"); 500 java_lang_ref_WeakReference->SetAccessFlags( 501 java_lang_ref_WeakReference->GetAccessFlags() | 502 kAccClassIsReference | kAccClassIsWeakReference); 503 504 // Setup the ClassLoader, verifying the object_size_. 505 mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;"); 506 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize()); 507 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader); 508 509 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and 510 // java.lang.StackTraceElement as a convenience. 511 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;")); 512 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable)); 513 SetClassRoot(kJavaLangClassNotFoundException, 514 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;")); 515 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;")); 516 SetClassRoot(kJavaLangStackTraceElementArrayClass, 517 FindSystemClass(self, "[Ljava/lang/StackTraceElement;")); 518 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement)); 519 520 FinishInit(self); 521 522 VLOG(startup) << "ClassLinker::InitFromCompiler exiting"; 523} 524 525void ClassLinker::FinishInit(Thread* self) { 526 VLOG(startup) << "ClassLinker::FinishInit entering"; 527 528 // Let the heap know some key offsets into java.lang.ref instances 529 // Note: we hard code the field indexes here rather than using FindInstanceField 530 // as the types of the field can't be resolved prior to the runtime being 531 // fully initialized 532 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference); 533 mirror::Class* java_lang_ref_FinalizerReference = 534 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;"); 535 536 mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0); 537 CHECK_STREQ(pendingNext->GetName(), "pendingNext"); 538 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;"); 539 540 mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1); 541 CHECK_STREQ(queue->GetName(), "queue"); 542 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;"); 543 544 mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2); 545 CHECK_STREQ(queueNext->GetName(), "queueNext"); 546 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;"); 547 548 mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3); 549 CHECK_STREQ(referent->GetName(), "referent"); 550 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;"); 551 552 mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2); 553 CHECK_STREQ(zombie->GetName(), "zombie"); 554 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;"); 555 556 // ensure all class_roots_ are initialized 557 for (size_t i = 0; i < kClassRootsMax; i++) { 558 ClassRoot class_root = static_cast<ClassRoot>(i); 559 mirror::Class* klass = GetClassRoot(class_root); 560 CHECK(klass != nullptr); 561 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr); 562 // note SetClassRoot does additional validation. 563 // if possible add new checks there to catch errors early 564 } 565 566 CHECK(!array_iftable_.IsNull()); 567 568 // disable the slow paths in FindClass and CreatePrimitiveClass now 569 // that Object, Class, and Object[] are setup 570 init_done_ = true; 571 572 VLOG(startup) << "ClassLinker::FinishInit exiting"; 573} 574 575void ClassLinker::RunRootClinits() { 576 Thread* self = Thread::Current(); 577 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) { 578 mirror::Class* c = GetClassRoot(ClassRoot(i)); 579 if (!c->IsArrayClass() && !c->IsPrimitive()) { 580 StackHandleScope<1> hs(self); 581 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i)))); 582 EnsureInitialized(h_class, true, true); 583 self->AssertNoPendingException(); 584 } 585 } 586} 587 588bool ClassLinker::GenerateOatFile(const char* dex_filename, 589 int oat_fd, 590 const char* oat_cache_filename, 591 std::string* error_msg) { 592 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC. 593 std::string dex2oat(Runtime::Current()->GetCompilerExecutable()); 594 595 gc::Heap* heap = Runtime::Current()->GetHeap(); 596 std::string boot_image_option("--boot-image="); 597 if (heap->GetImageSpace() == nullptr) { 598 // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely 599 // out of space anyway it might not matter. 600 *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running " 601 "without an image.", dex_filename); 602 return false; 603 } 604 boot_image_option += heap->GetImageSpace()->GetImageLocation(); 605 606 std::string dex_file_option("--dex-file="); 607 dex_file_option += dex_filename; 608 609 std::string oat_fd_option("--oat-fd="); 610 StringAppendF(&oat_fd_option, "%d", oat_fd); 611 612 std::string oat_location_option("--oat-location="); 613 oat_location_option += oat_cache_filename; 614 615 std::vector<std::string> argv; 616 argv.push_back(dex2oat); 617 argv.push_back("--runtime-arg"); 618 argv.push_back("-classpath"); 619 argv.push_back("--runtime-arg"); 620 argv.push_back(Runtime::Current()->GetClassPathString()); 621 622 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv); 623 624 if (!Runtime::Current()->IsVerificationEnabled()) { 625 argv.push_back("--compiler-filter=verify-none"); 626 } 627 628 if (Runtime::Current()->MustRelocateIfPossible()) { 629 argv.push_back("--runtime-arg"); 630 argv.push_back("-Xrelocate"); 631 } else { 632 argv.push_back("--runtime-arg"); 633 argv.push_back("-Xnorelocate"); 634 } 635 636 if (!kIsTargetBuild) { 637 argv.push_back("--host"); 638 } 639 640 argv.push_back(boot_image_option); 641 argv.push_back(dex_file_option); 642 argv.push_back(oat_fd_option); 643 argv.push_back(oat_location_option); 644 const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions(); 645 for (size_t i = 0; i < compiler_options.size(); ++i) { 646 argv.push_back(compiler_options[i].c_str()); 647 } 648 649 return Exec(argv, error_msg); 650} 651 652const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) { 653 WriterMutexLock mu(Thread::Current(), dex_lock_); 654 if (kIsDebugBuild) { 655 for (size_t i = 0; i < oat_files_.size(); ++i) { 656 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation(); 657 } 658 } 659 VLOG(class_linker) << "Registering " << oat_file->GetLocation(); 660 oat_files_.push_back(oat_file); 661 return oat_file; 662} 663 664OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) { 665 VLOG(startup) << "ClassLinker::GetImageOatFile entering"; 666 OatFile* oat_file = space->ReleaseOatFile(); 667 CHECK_EQ(RegisterOatFile(oat_file), oat_file); 668 VLOG(startup) << "ClassLinker::GetImageOatFile exiting"; 669 return *oat_file; 670} 671 672const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) { 673 const char* dex_location = dex_file.GetLocation().c_str(); 674 uint32_t dex_location_checksum = dex_file.GetLocationChecksum(); 675 return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum); 676} 677 678const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location, 679 const char* dex_location, 680 const uint32_t* dex_location_checksum) { 681 ReaderMutexLock mu(Thread::Current(), dex_lock_); 682 for (const OatFile* oat_file : oat_files_) { 683 DCHECK(oat_file != nullptr); 684 685 if (oat_location != nullptr) { 686 if (oat_file->GetLocation() != oat_location) { 687 continue; 688 } 689 } 690 691 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, 692 dex_location_checksum, 693 false); 694 if (oat_dex_file != nullptr) { 695 return oat_dex_file; 696 } 697 } 698 return nullptr; 699} 700 701 702// Loads all multi dex files from the given oat file returning true on success. 703// 704// Parameters: 705// oat_file - the oat file to load from 706// dex_location - the dex location used to generate the oat file 707// dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files) 708// generated - whether or not the oat_file existed before or was just (re)generated 709// error_msgs - any error messages will be appended here 710// dex_files - the loaded dex_files will be appended here (only if the loading succeeds) 711static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file, 712 const char* dex_location, 713 const uint32_t* dex_location_checksum, 714 bool generated, 715 std::vector<std::string>* error_msgs, 716 std::vector<const DexFile*>* dex_files) { 717 if (oat_file == nullptr) { 718 return false; 719 } 720 721 size_t old_size = dex_files->size(); // To rollback on error. 722 723 bool success = true; 724 for (size_t i = 0; success; ++i) { 725 std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location); 726 const char* next_name = next_name_str.c_str(); 727 728 uint32_t next_location_checksum; 729 uint32_t* next_location_checksum_pointer = &next_location_checksum; 730 std::string error_msg; 731 if ((i == 0) && (strcmp(next_name, dex_location) == 0)) { 732 // When i=0 the multidex name should be the same as the location name. We already have the 733 // checksum it so we don't need to recompute it. 734 if (dex_location_checksum == nullptr) { 735 next_location_checksum_pointer = nullptr; 736 } else { 737 next_location_checksum = *dex_location_checksum; 738 } 739 } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) { 740 DCHECK_EQ(false, i == 0 && generated); 741 next_location_checksum_pointer = nullptr; 742 } 743 744 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false); 745 746 if (oat_dex_file == nullptr) { 747 if (i == 0 && generated) { 748 std::string error_msg; 749 error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out " 750 " file'%s'", dex_location, next_location_checksum, 751 oat_file->GetLocation().c_str()); 752 error_msgs->push_back(error_msg); 753 } 754 break; // Not found, done. 755 } 756 757 // Checksum test. Test must succeed when generated. 758 success = !generated; 759 if (next_location_checksum_pointer != nullptr) { 760 success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum(); 761 } 762 763 if (success) { 764 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg); 765 if (dex_file == nullptr) { 766 success = false; 767 error_msgs->push_back(error_msg); 768 } else { 769 dex_files->push_back(dex_file); 770 } 771 } 772 773 // When we generated the file, we expect success, or something is terribly wrong. 774 CHECK_EQ(false, generated && !success) 775 << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str() 776 << std::hex << " dex_location_checksum=" << next_location_checksum 777 << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum(); 778 } 779 780 if (dex_files->size() == old_size) { 781 success = false; // We did not even find classes.dex 782 } 783 784 if (success) { 785 return true; 786 } else { 787 // Free all the dex files we have loaded. 788 auto it = dex_files->begin() + old_size; 789 auto it_end = dex_files->end(); 790 for (; it != it_end; it++) { 791 delete *it; 792 } 793 dex_files->erase(dex_files->begin() + old_size, it_end); 794 795 return false; 796 } 797} 798 799// Multidex files make it possible that some, but not all, dex files can be broken/outdated. This 800// complicates the loading process, as we should not use an iterative loading process, because that 801// would register the oat file and dex files that come before the broken one. Instead, check all 802// multidex ahead of time. 803bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location, 804 std::vector<std::string>* error_msgs, 805 std::vector<const DexFile*>* dex_files) { 806 // 1) Check whether we have an open oat file. 807 // This requires a dex checksum, use the "primary" one. 808 uint32_t dex_location_checksum; 809 uint32_t* dex_location_checksum_pointer = &dex_location_checksum; 810 bool have_checksum = true; 811 std::string checksum_error_msg; 812 if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) { 813 // This happens for pre-opted files since the corresponding dex files are no longer on disk. 814 dex_location_checksum_pointer = nullptr; 815 have_checksum = false; 816 } 817 818 bool needs_registering = false; 819 820 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location, 821 dex_location_checksum_pointer); 822 std::unique_ptr<const OatFile> open_oat_file( 823 oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr); 824 825 // 2) If we do not have an open one, maybe there's one on disk already. 826 827 // In case the oat file is not open, we play a locking game here so 828 // that if two different processes race to load and register or generate 829 // (or worse, one tries to open a partial generated file) we will be okay. 830 // This is actually common with apps that use DexClassLoader to work 831 // around the dex method reference limit and that have a background 832 // service running in a separate process. 833 ScopedFlock scoped_flock; 834 835 if (open_oat_file.get() == nullptr) { 836 if (oat_location != nullptr) { 837 // Can only do this if we have a checksum, else error. 838 if (!have_checksum) { 839 error_msgs->push_back(checksum_error_msg); 840 return false; 841 } 842 843 std::string error_msg; 844 845 // We are loading or creating one in the future. Time to set up the file lock. 846 if (!scoped_flock.Init(oat_location, &error_msg)) { 847 error_msgs->push_back(error_msg); 848 return false; 849 } 850 851 // TODO Caller specifically asks for this oat_location. We should honor it. Probably? 852 open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum, 853 oat_location, &error_msg)); 854 855 if (open_oat_file.get() == nullptr) { 856 std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s", 857 dex_location, oat_location, error_msg.c_str()); 858 VLOG(class_linker) << compound_msg; 859 error_msgs->push_back(compound_msg); 860 } 861 } else { 862 // TODO: What to lock here? 863 bool obsolete_file_cleanup_failed; 864 open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location, 865 dex_location_checksum_pointer, 866 kRuntimeISA, error_msgs, 867 &obsolete_file_cleanup_failed)); 868 // There's no point in going forward and eventually try to regenerate the 869 // file if we couldn't remove the obsolete one. Mostly likely we will fail 870 // with the same error when trying to write the new file. 871 // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS). 872 if (obsolete_file_cleanup_failed) { 873 return false; 874 } 875 } 876 needs_registering = true; 877 } 878 879 // 3) If we have an oat file, check all contained multidex files for our dex_location. 880 // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument. 881 bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location, 882 dex_location_checksum_pointer, 883 false, error_msgs, dex_files); 884 if (success) { 885 const OatFile* oat_file = open_oat_file.release(); // Avoid deleting it. 886 if (needs_registering) { 887 // We opened the oat file, so we must register it. 888 RegisterOatFile(oat_file); 889 } 890 // If the file isn't executable we failed patchoat but did manage to get the dex files. 891 return oat_file->IsExecutable(); 892 } else { 893 if (needs_registering) { 894 // We opened it, delete it. 895 open_oat_file.reset(); 896 } else { 897 open_oat_file.release(); // Do not delete open oat files. 898 } 899 } 900 901 // 4) If it's not the case (either no oat file or mismatches), regenerate and load. 902 903 // Need a checksum, fail else. 904 if (!have_checksum) { 905 error_msgs->push_back(checksum_error_msg); 906 return false; 907 } 908 909 // Look in cache location if no oat_location is given. 910 std::string cache_location; 911 if (oat_location == nullptr) { 912 // Use the dalvik cache. 913 const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA))); 914 cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str()); 915 oat_location = cache_location.c_str(); 916 } 917 918 bool has_flock = true; 919 // Definitely need to lock now. 920 if (!scoped_flock.HasFile()) { 921 std::string error_msg; 922 if (!scoped_flock.Init(oat_location, &error_msg)) { 923 error_msgs->push_back(error_msg); 924 has_flock = false; 925 } 926 } 927 928 if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) { 929 // Create the oat file. 930 open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(), 931 oat_location, error_msgs)); 932 } 933 934 // Failed, bail. 935 if (open_oat_file.get() == nullptr) { 936 std::string error_msg; 937 // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress. 938 DexFile::Open(dex_location, dex_location, &error_msg, dex_files); 939 error_msgs->push_back(error_msg); 940 return false; 941 } 942 943 // Try to load again, but stronger checks. 944 success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location, 945 dex_location_checksum_pointer, 946 true, error_msgs, dex_files); 947 if (success) { 948 RegisterOatFile(open_oat_file.release()); 949 return true; 950 } else { 951 return false; 952 } 953} 954 955const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location, 956 uint32_t dex_location_checksum, 957 const char* oat_location, 958 std::string* error_msg) { 959 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr, 960 !Runtime::Current()->IsCompiler(), 961 error_msg)); 962 if (oat_file.get() == nullptr) { 963 *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location, 964 error_msg->c_str()); 965 return nullptr; 966 } 967 Runtime* runtime = Runtime::Current(); 968 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace(); 969 if (image_space != nullptr) { 970 const ImageHeader& image_header = image_space->GetImageHeader(); 971 uint32_t expected_image_oat_checksum = image_header.GetOatChecksum(); 972 uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum(); 973 if (expected_image_oat_checksum != actual_image_oat_checksum) { 974 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of " 975 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum, 976 actual_image_oat_checksum); 977 return nullptr; 978 } 979 980 uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()); 981 uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(); 982 if (expected_image_oat_offset != actual_image_oat_offset) { 983 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %" 984 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset, 985 actual_image_oat_offset); 986 return nullptr; 987 } 988 int32_t expected_patch_delta = image_header.GetPatchDelta(); 989 int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta(); 990 if (expected_patch_delta != actual_patch_delta) { 991 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, " 992 " found %d", oat_location, expected_patch_delta, actual_patch_delta); 993 return nullptr; 994 } 995 } 996 997 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, 998 &dex_location_checksum); 999 if (oat_dex_file == nullptr) { 1000 *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location, 1001 dex_location); 1002 return nullptr; 1003 } 1004 uint32_t expected_dex_checksum = dex_location_checksum; 1005 uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum(); 1006 if (expected_dex_checksum != actual_dex_checksum) { 1007 *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, " 1008 "found 0x%x", oat_location, expected_dex_checksum, 1009 actual_dex_checksum); 1010 return nullptr; 1011 } 1012 std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg)); 1013 if (dex_file.get() != nullptr) { 1014 return oat_file.release(); 1015 } else { 1016 return nullptr; 1017 } 1018} 1019 1020const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location, 1021 int fd, const char* oat_location, 1022 std::vector<std::string>* error_msgs) { 1023 // Generate the output oat file for the dex file 1024 VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location; 1025 std::string error_msg; 1026 if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) { 1027 CHECK(!error_msg.empty()); 1028 error_msgs->push_back(error_msg); 1029 return nullptr; 1030 } 1031 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr, nullptr, 1032 !Runtime::Current()->IsCompiler(), 1033 &error_msg)); 1034 if (oat_file.get() == nullptr) { 1035 std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s", 1036 oat_location, error_msg.c_str()); 1037 error_msgs->push_back(compound_msg); 1038 return nullptr; 1039 } 1040 1041 return oat_file.release(); 1042} 1043 1044bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file, 1045 const InstructionSet instruction_set) { 1046 Runtime* runtime = Runtime::Current(); 1047 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace(); 1048 if (image_space == nullptr) { 1049 return false; 1050 } 1051 uint32_t image_oat_checksum = 0; 1052 if (instruction_set == kRuntimeISA) { 1053 const ImageHeader& image_header = image_space->GetImageHeader(); 1054 image_oat_checksum = image_header.GetOatChecksum(); 1055 } else { 1056 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie( 1057 image_space->GetImageLocation().c_str(), instruction_set)); 1058 image_oat_checksum = image_header->GetOatChecksum(); 1059 } 1060 return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum; 1061} 1062 1063bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file, 1064 const InstructionSet instruction_set, 1065 std::string* error_msg) { 1066 Runtime* runtime = Runtime::Current(); 1067 const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace(); 1068 if (image_space == nullptr) { 1069 *error_msg = "No image space for verification against"; 1070 return false; 1071 } 1072 1073 // If the requested instruction set is the same as the current runtime, 1074 // we can use the checksums directly. If it isn't, we'll have to read the 1075 // image header from the image for the right instruction set. 1076 uint32_t image_oat_checksum = 0; 1077 uintptr_t image_oat_data_begin = 0; 1078 int32_t image_patch_delta = 0; 1079 if (instruction_set == runtime->GetInstructionSet()) { 1080 const ImageHeader& image_header = image_space->GetImageHeader(); 1081 image_oat_checksum = image_header.GetOatChecksum(); 1082 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()); 1083 image_patch_delta = image_header.GetPatchDelta(); 1084 } else { 1085 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie( 1086 image_space->GetImageLocation().c_str(), instruction_set)); 1087 image_oat_checksum = image_header->GetOatChecksum(); 1088 image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin()); 1089 image_patch_delta = image_header->GetPatchDelta(); 1090 } 1091 const OatHeader& oat_header = oat_file->GetOatHeader(); 1092 bool ret = (oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum); 1093 1094 // If the oat file is PIC, it doesn't care if/how image was relocated. Ignore these checks. 1095 if (!oat_file->IsPic()) { 1096 ret = ret && (oat_header.GetImagePatchDelta() == image_patch_delta) 1097 && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin); 1098 } 1099 if (!ret) { 1100 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)", 1101 oat_file->GetLocation().c_str(), 1102 oat_file->GetOatHeader().GetImageFileLocationOatChecksum(), 1103 oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(), 1104 oat_file->GetOatHeader().GetImagePatchDelta(), 1105 image_oat_checksum, image_oat_data_begin, image_patch_delta); 1106 } 1107 return ret; 1108} 1109 1110bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file, 1111 const char* dex_location, 1112 uint32_t dex_location_checksum, 1113 const InstructionSet instruction_set, 1114 std::string* error_msg) { 1115 if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) { 1116 return false; 1117 } 1118 1119 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, 1120 &dex_location_checksum); 1121 if (oat_dex_file == nullptr) { 1122 *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x", 1123 oat_file->GetLocation().c_str(), dex_location, dex_location_checksum); 1124 for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) { 1125 *error_msg += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x", 1126 oat_file->GetLocation().c_str(), 1127 oat_dex_file->GetDexFileLocation().c_str(), 1128 oat_dex_file->GetDexFileLocationChecksum()); 1129 } 1130 return false; 1131 } 1132 1133 if (dex_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) { 1134 *error_msg = StringPrintf("oat file '%s' mismatch (0x%x) with '%s' (0x%x)", 1135 oat_file->GetLocation().c_str(), 1136 oat_dex_file->GetDexFileLocationChecksum(), 1137 dex_location, dex_location_checksum); 1138 return false; 1139 } 1140 return true; 1141} 1142 1143bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file, 1144 const char* dex_location, 1145 const uint32_t* dex_location_checksum, 1146 std::string* error_msg) { 1147 CHECK(oat_file != nullptr); 1148 CHECK(dex_location != nullptr); 1149 std::unique_ptr<const DexFile> dex_file; 1150 if (dex_location_checksum == nullptr) { 1151 // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is 1152 // up-to-date. This is the common case in user builds for jar's and apk's in the /system 1153 // directory. 1154 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr); 1155 if (oat_dex_file == nullptr) { 1156 *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat " 1157 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location, 1158 error_msg->c_str()); 1159 return false; 1160 } 1161 dex_file.reset(oat_dex_file->OpenDexFile(error_msg)); 1162 } else { 1163 bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum, 1164 kRuntimeISA, error_msg); 1165 if (!verified) { 1166 return false; 1167 } 1168 dex_file.reset(oat_file->GetOatDexFile(dex_location, 1169 dex_location_checksum)->OpenDexFile(error_msg)); 1170 } 1171 return dex_file.get() != nullptr; 1172} 1173 1174const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation( 1175 const char* dex_location, 1176 const uint32_t* dex_location_checksum, 1177 InstructionSet isa, 1178 std::vector<std::string>* error_msgs, 1179 bool* obsolete_file_cleanup_failed) { 1180 *obsolete_file_cleanup_failed = false; 1181 bool already_opened = false; 1182 std::string dex_location_str(dex_location); 1183 std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa, 1184 &already_opened, 1185 obsolete_file_cleanup_failed, 1186 error_msgs)); 1187 std::string error_msg; 1188 if (oat_file.get() == nullptr) { 1189 error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'", 1190 dex_location)); 1191 return nullptr; 1192 } else if (oat_file->IsExecutable() && 1193 !VerifyOatWithDexFile(oat_file.get(), dex_location, 1194 dex_location_checksum, &error_msg)) { 1195 error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location " 1196 "'%s': %s", oat_file->GetLocation().c_str(), dex_location, 1197 error_msg.c_str())); 1198 return nullptr; 1199 } else if (!oat_file->IsExecutable() && 1200 Runtime::Current()->GetHeap()->HasImageSpace() && 1201 !VerifyOatImageChecksum(oat_file.get(), isa)) { 1202 error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for " 1203 "dex location '%s'. Image checksum incorrect.", 1204 oat_file->GetLocation().c_str(), dex_location)); 1205 return nullptr; 1206 } else { 1207 return oat_file.release(); 1208 } 1209} 1210 1211const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) { 1212 ReaderMutexLock mu(Thread::Current(), dex_lock_); 1213 for (size_t i = 0; i < oat_files_.size(); i++) { 1214 const OatFile* oat_file = oat_files_[i]; 1215 DCHECK(oat_file != nullptr); 1216 if (oat_file->GetLocation() == oat_location) { 1217 return oat_file; 1218 } 1219 } 1220 return nullptr; 1221} 1222 1223const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location, 1224 InstructionSet isa, 1225 bool *already_opened, 1226 bool *obsolete_file_cleanup_failed, 1227 std::vector<std::string>* error_msgs) { 1228 // Find out if we've already opened the file 1229 const OatFile* ret = nullptr; 1230 std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa)); 1231 ret = FindOpenedOatFileFromOatLocation(odex_filename); 1232 if (ret != nullptr) { 1233 *already_opened = true; 1234 return ret; 1235 } 1236 1237 std::string dalvik_cache; 1238 bool have_android_data = false; 1239 bool have_dalvik_cache = false; 1240 bool is_global_cache = false; 1241 GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache, 1242 &have_android_data, &have_dalvik_cache, &is_global_cache); 1243 std::string cache_filename; 1244 if (have_dalvik_cache) { 1245 cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str()); 1246 ret = FindOpenedOatFileFromOatLocation(cache_filename); 1247 if (ret != nullptr) { 1248 *already_opened = true; 1249 return ret; 1250 } 1251 } else { 1252 // If we need to relocate we should just place odex back where it started. 1253 cache_filename = odex_filename; 1254 } 1255 1256 ret = nullptr; 1257 1258 // We know that neither the odex nor the cache'd version is already in use, if it even exists. 1259 // 1260 // Now we do the following: 1261 // 1) Try and open the odex version 1262 // 2) If present, checksum-verified & relocated correctly return it 1263 // 3) Close the odex version to free up its address space. 1264 // 4) Try and open the cache version 1265 // 5) If present, checksum-verified & relocated correctly return it 1266 // 6) Close the cache version to free up its address space. 1267 // 7) If we should relocate: 1268 // a) If we have opened and checksum-verified the odex version relocate it to 1269 // 'cache_filename' and return it 1270 // b) If we have opened and checksum-verified the cache version relocate it in place and return 1271 // it. This should not happen often (I think only the run-test's will hit this case). 1272 // 8) If the cache-version was present we should delete it since it must be obsolete if we get to 1273 // this point. 1274 // 9) Return nullptr 1275 1276 *already_opened = false; 1277 const Runtime* runtime = Runtime::Current(); 1278 CHECK(runtime != nullptr); 1279 bool executable = !runtime->IsCompiler(); 1280 1281 std::string odex_error_msg; 1282 bool should_patch_system = false; 1283 bool odex_checksum_verified = false; 1284 bool have_system_odex = false; 1285 { 1286 // There is a high probability that both these oat files map similar/the same address 1287 // spaces so we must scope them like this so they each gets its turn. 1288 std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr, 1289 nullptr, 1290 executable, &odex_error_msg)); 1291 if (odex_oat_file.get() != nullptr && CheckOatFile(runtime, odex_oat_file.get(), isa, 1292 &odex_checksum_verified, 1293 &odex_error_msg)) { 1294 error_msgs->push_back(odex_error_msg); 1295 return odex_oat_file.release(); 1296 } else { 1297 if (odex_checksum_verified) { 1298 // We can just relocate 1299 should_patch_system = true; 1300 odex_error_msg = "Image Patches are incorrect"; 1301 } 1302 if (odex_oat_file.get() != nullptr) { 1303 have_system_odex = true; 1304 } 1305 } 1306 } 1307 1308 std::string cache_error_msg; 1309 bool should_patch_cache = false; 1310 bool cache_checksum_verified = false; 1311 if (have_dalvik_cache) { 1312 std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr, 1313 nullptr, 1314 executable, &cache_error_msg)); 1315 if (cache_oat_file.get() != nullptr && CheckOatFile(runtime, cache_oat_file.get(), isa, 1316 &cache_checksum_verified, 1317 &cache_error_msg)) { 1318 error_msgs->push_back(cache_error_msg); 1319 return cache_oat_file.release(); 1320 } else if (cache_checksum_verified) { 1321 // We can just relocate 1322 should_patch_cache = true; 1323 cache_error_msg = "Image Patches are incorrect"; 1324 } 1325 } else if (have_android_data) { 1326 // dalvik_cache does not exist but android data does. This means we should be able to create 1327 // it, so we should try. 1328 GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true); 1329 } 1330 1331 ret = nullptr; 1332 std::string error_msg; 1333 if (runtime->CanRelocate()) { 1334 // Run relocation 1335 gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace(); 1336 if (space != nullptr) { 1337 const std::string& image_location = space->GetImageLocation(); 1338 if (odex_checksum_verified && should_patch_system) { 1339 ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg); 1340 } else if (cache_checksum_verified && should_patch_cache) { 1341 CHECK(have_dalvik_cache); 1342 ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg); 1343 } 1344 } else if (have_system_odex) { 1345 ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg); 1346 } 1347 } 1348 if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) { 1349 // implicitly: were able to fine where the cached version is but we were unable to use it, 1350 // either as a destination for relocation or to open a file. We should delete it if it is 1351 // there. 1352 if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) { 1353 std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when " 1354 "searching for dex file %s: %s", 1355 cache_filename.c_str(), dex_location.c_str(), 1356 strerror(errno)); 1357 error_msgs->push_back(rm_error_msg); 1358 VLOG(class_linker) << rm_error_msg; 1359 // Let the caller know that we couldn't remove the obsolete file. 1360 // This is a good indication that further writes may fail as well. 1361 *obsolete_file_cleanup_failed = true; 1362 } 1363 } 1364 if (ret == nullptr) { 1365 VLOG(class_linker) << error_msg; 1366 error_msgs->push_back(error_msg); 1367 std::string relocation_msg; 1368 if (runtime->CanRelocate()) { 1369 relocation_msg = StringPrintf(" and relocation failed"); 1370 } 1371 if (have_dalvik_cache && cache_checksum_verified) { 1372 error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s " 1373 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(), 1374 cache_filename.c_str(), cache_error_msg.c_str(), 1375 relocation_msg.c_str()); 1376 } else { 1377 error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no " 1378 "dalvik_cache availible)%s.", odex_filename.c_str(), 1379 odex_error_msg.c_str(), relocation_msg.c_str()); 1380 } 1381 VLOG(class_linker) << error_msg; 1382 error_msgs->push_back(error_msg); 1383 } 1384 return ret; 1385} 1386 1387const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path, 1388 InstructionSet isa, 1389 std::string* error_msg) { 1390 // We open it non-executable 1391 std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, nullptr, false, error_msg)); 1392 if (output.get() == nullptr) { 1393 return nullptr; 1394 } 1395 if (!Runtime::Current()->GetHeap()->HasImageSpace() || 1396 VerifyOatImageChecksum(output.get(), isa)) { 1397 return output.release(); 1398 } else { 1399 *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.", 1400 oat_path.c_str()); 1401 return nullptr; 1402 } 1403} 1404 1405const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat, 1406 const std::string& output_oat, 1407 const std::string& image_location, 1408 InstructionSet isa, 1409 std::string* error_msg) { 1410 Runtime* runtime = Runtime::Current(); 1411 DCHECK(runtime != nullptr); 1412 if (!runtime->GetHeap()->HasImageSpace()) { 1413 // We don't have an image space so there is no point in trying to patchoat. 1414 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are " 1415 << "running without an image. Attempting to use oat file for interpretation."; 1416 return GetInterpretedOnlyOat(input_oat, isa, error_msg); 1417 } 1418 if (!runtime->IsDex2OatEnabled()) { 1419 // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the 1420 // input_oat but make sure we only do interpretation on it's dex files. 1421 LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being " 1422 << "disabled. Attempting to use oat file for interpretation"; 1423 return GetInterpretedOnlyOat(input_oat, isa, error_msg); 1424 } 1425 Locks::mutator_lock_->AssertNotHeld(Thread::Current()); // Avoid starving GC. 1426 std::string patchoat(runtime->GetPatchoatExecutable()); 1427 1428 std::string isa_arg("--instruction-set="); 1429 isa_arg += GetInstructionSetString(isa); 1430 std::string input_oat_filename_arg("--input-oat-file="); 1431 input_oat_filename_arg += input_oat; 1432 std::string output_oat_filename_arg("--output-oat-file="); 1433 output_oat_filename_arg += output_oat; 1434 std::string patched_image_arg("--patched-image-location="); 1435 patched_image_arg += image_location; 1436 1437 std::vector<std::string> argv; 1438 argv.push_back(patchoat); 1439 argv.push_back(isa_arg); 1440 argv.push_back(input_oat_filename_arg); 1441 argv.push_back(output_oat_filename_arg); 1442 argv.push_back(patched_image_arg); 1443 1444 std::string command_line(Join(argv, ' ')); 1445 LOG(INFO) << "Relocate Oat File: " << command_line; 1446 bool success = Exec(argv, error_msg); 1447 if (success) { 1448 std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr, nullptr, 1449 !runtime->IsCompiler(), error_msg)); 1450 bool checksum_verified = false; 1451 if (output.get() != nullptr && CheckOatFile(runtime, output.get(), isa, &checksum_verified, 1452 error_msg)) { 1453 return output.release(); 1454 } else if (output.get() != nullptr) { 1455 *error_msg = StringPrintf("Patching of oat file '%s' succeeded " 1456 "but output file '%s' failed verifcation: %s", 1457 input_oat.c_str(), output_oat.c_str(), error_msg->c_str()); 1458 } else { 1459 *error_msg = StringPrintf("Patching of oat file '%s' succeeded " 1460 "but was unable to open output file '%s': %s", 1461 input_oat.c_str(), output_oat.c_str(), error_msg->c_str()); 1462 } 1463 } else if (!runtime->IsCompiler()) { 1464 // patchoat failed which means we probably don't have enough room to place the output oat file, 1465 // instead of failing we should just run the interpreter from the dex files in the input oat. 1466 LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file " 1467 << "for interpretation. patchoat failure was: " << *error_msg; 1468 return GetInterpretedOnlyOat(input_oat, isa, error_msg); 1469 } else { 1470 *error_msg = StringPrintf("Patching of oat file '%s to '%s' " 1471 "failed: %s", input_oat.c_str(), output_oat.c_str(), 1472 error_msg->c_str()); 1473 } 1474 return nullptr; 1475} 1476 1477bool ClassLinker::CheckOatFile(const Runtime* runtime, const OatFile* oat_file, InstructionSet isa, 1478 bool* checksum_verified, 1479 std::string* error_msg) { 1480 std::string compound_msg("Oat file failed to verify: "); 1481 uint32_t real_image_checksum; 1482 void* real_image_oat_offset; 1483 int32_t real_patch_delta; 1484 const gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace(); 1485 if (image_space == nullptr) { 1486 *error_msg = "No image space present"; 1487 return false; 1488 } 1489 if (isa == Runtime::Current()->GetInstructionSet()) { 1490 const ImageHeader& image_header = image_space->GetImageHeader(); 1491 real_image_checksum = image_header.GetOatChecksum(); 1492 real_image_oat_offset = image_header.GetOatDataBegin(); 1493 real_patch_delta = image_header.GetPatchDelta(); 1494 } else { 1495 std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie( 1496 image_space->GetImageLocation().c_str(), isa)); 1497 real_image_checksum = image_header->GetOatChecksum(); 1498 real_image_oat_offset = image_header->GetOatDataBegin(); 1499 real_patch_delta = image_header->GetPatchDelta(); 1500 } 1501 1502 const OatHeader& oat_header = oat_file->GetOatHeader(); 1503 1504 uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum(); 1505 *checksum_verified = oat_image_checksum == real_image_checksum; 1506 if (!*checksum_verified) { 1507 compound_msg += StringPrintf(" Oat Image Checksum Incorrect (expected 0x%x, recieved 0x%x)", 1508 real_image_checksum, oat_image_checksum); 1509 } 1510 1511 bool offset_verified; 1512 bool patch_delta_verified; 1513 1514 if (!oat_file->IsPic()) { 1515 void* oat_image_oat_offset = 1516 reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin()); 1517 offset_verified = oat_image_oat_offset == real_image_oat_offset; 1518 if (!offset_verified) { 1519 compound_msg += StringPrintf(" Oat Image oat offset incorrect (expected 0x%p, recieved 0x%p)", 1520 real_image_oat_offset, oat_image_oat_offset); 1521 } 1522 1523 int32_t oat_patch_delta = oat_header.GetImagePatchDelta(); 1524 patch_delta_verified = oat_patch_delta == real_patch_delta; 1525 if (!patch_delta_verified) { 1526 compound_msg += StringPrintf(" Oat image patch delta incorrect (expected 0x%x, recieved 0x%x)", 1527 real_patch_delta, oat_patch_delta); 1528 } 1529 } else { 1530 // If an oat file is PIC, we ignore offset and patching delta. 1531 offset_verified = true; 1532 patch_delta_verified = true; 1533 } 1534 1535 bool ret = (*checksum_verified && offset_verified && patch_delta_verified); 1536 if (ret) { 1537 *error_msg = compound_msg; 1538 } 1539 return ret; 1540} 1541 1542const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location, 1543 std::string* error_msg) { 1544 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location); 1545 if (oat_file != nullptr) { 1546 return oat_file; 1547 } 1548 1549 return OatFile::Open(oat_location, oat_location, nullptr, nullptr, !Runtime::Current()->IsCompiler(), 1550 error_msg); 1551} 1552 1553static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) 1554 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1555 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg); 1556 1557 DCHECK(obj != nullptr); 1558 DCHECK(class_linker != nullptr); 1559 1560 if (obj->IsArtMethod()) { 1561 mirror::ArtMethod* method = obj->AsArtMethod(); 1562 if (!method->IsNative()) { 1563 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge); 1564 if (method != Runtime::Current()->GetResolutionMethod()) { 1565 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge()); 1566#if defined(ART_USE_PORTABLE_COMPILER) 1567 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge()); 1568#endif 1569 } 1570 } 1571 } 1572} 1573 1574void ClassLinker::InitFromImage() { 1575 VLOG(startup) << "ClassLinker::InitFromImage entering"; 1576 CHECK(!init_done_); 1577 1578 Thread* self = Thread::Current(); 1579 gc::Heap* heap = Runtime::Current()->GetHeap(); 1580 gc::space::ImageSpace* space = heap->GetImageSpace(); 1581 dex_cache_image_class_lookup_required_ = true; 1582 CHECK(space != nullptr); 1583 OatFile& oat_file = GetImageOatFile(space); 1584 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U); 1585 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U); 1586 const char* image_file_location = oat_file.GetOatHeader(). 1587 GetStoreValueByKey(OatHeader::kImageLocationKey); 1588 CHECK(image_file_location == nullptr || *image_file_location == 0); 1589 portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline(); 1590 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline(); 1591 portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline(); 1592 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline(); 1593 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline(); 1594 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge(); 1595 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches); 1596 mirror::ObjectArray<mirror::DexCache>* dex_caches = 1597 dex_caches_object->AsObjectArray<mirror::DexCache>(); 1598 1599 StackHandleScope<1> hs(self); 1600 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle( 1601 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)-> 1602 AsObjectArray<mirror::Class>())); 1603 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get()); 1604 1605 // Special case of setting up the String class early so that we can test arbitrary objects 1606 // as being Strings or not 1607 mirror::String::SetClass(GetClassRoot(kJavaLangString)); 1608 1609 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(), 1610 static_cast<uint32_t>(dex_caches->GetLength())); 1611 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 1612 StackHandleScope<1> hs(self); 1613 Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i))); 1614 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8()); 1615 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(), 1616 nullptr); 1617 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location; 1618 std::string error_msg; 1619 const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg); 1620 if (dex_file == nullptr) { 1621 LOG(FATAL) << "Failed to open dex file " << dex_file_location 1622 << " from within oat file " << oat_file.GetLocation() 1623 << " error '" << error_msg << "'"; 1624 } 1625 1626 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum()); 1627 1628 AppendToBootClassPath(*dex_file, dex_cache); 1629 } 1630 1631 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live 1632 // bitmap walk. 1633 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod)); 1634 1635 // Set entry point to interpreter if in InterpretOnly mode. 1636 if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) { 1637 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_); 1638 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this); 1639 } 1640 1641 // reinit class_roots_ 1642 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass)); 1643 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get()); 1644 1645 // reinit array_iftable_ from any array class instance, they should be == 1646 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable()); 1647 DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable()); 1648 // String class root was set above 1649 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference)); 1650 mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField)); 1651 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass)); 1652 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass)); 1653 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass)); 1654 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass)); 1655 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass)); 1656 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass)); 1657 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass)); 1658 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass)); 1659 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable)); 1660 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement)); 1661 1662 FinishInit(self); 1663 1664 VLOG(startup) << "ClassLinker::InitFromImage exiting"; 1665} 1666 1667void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) { 1668 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 1669 if ((flags & kVisitRootFlagAllRoots) != 0) { 1670 for (GcRoot<mirror::Class>& root : class_table_) { 1671 root.VisitRoot(callback, arg, 0, kRootStickyClass); 1672 } 1673 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) { 1674 root.VisitRoot(callback, arg, 0, kRootStickyClass); 1675 } 1676 } else if ((flags & kVisitRootFlagNewRoots) != 0) { 1677 for (auto& root : new_class_roots_) { 1678 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>(); 1679 root.VisitRoot(callback, arg, 0, kRootStickyClass); 1680 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>(); 1681 if (UNLIKELY(new_ref != old_ref)) { 1682 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the 1683 // corresponding object. This is slow, but luckily for us, this may only happen with a 1684 // concurrent moving GC. 1685 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref)); 1686 class_table_.Erase(it); 1687 class_table_.Insert(GcRoot<mirror::Class>(new_ref)); 1688 } 1689 } 1690 } 1691 if ((flags & kVisitRootFlagClearRootLog) != 0) { 1692 new_class_roots_.clear(); 1693 } 1694 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) { 1695 log_new_class_table_roots_ = true; 1696 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) { 1697 log_new_class_table_roots_ = false; 1698 } 1699 // We deliberately ignore the class roots in the image since we 1700 // handle image roots by using the MS/CMS rescanning of dirty cards. 1701} 1702 1703// Keep in sync with InitCallback. Anything we visit, we need to 1704// reinit references to when reinitializing a ClassLinker from a 1705// mapped image. 1706void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) { 1707 class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal); 1708 Thread* self = Thread::Current(); 1709 { 1710 ReaderMutexLock mu(self, dex_lock_); 1711 if ((flags & kVisitRootFlagAllRoots) != 0) { 1712 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) { 1713 dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal); 1714 } 1715 } else if ((flags & kVisitRootFlagNewRoots) != 0) { 1716 for (size_t index : new_dex_cache_roots_) { 1717 dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal); 1718 } 1719 } 1720 if ((flags & kVisitRootFlagClearRootLog) != 0) { 1721 new_dex_cache_roots_.clear(); 1722 } 1723 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) { 1724 log_new_dex_caches_roots_ = true; 1725 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) { 1726 log_new_dex_caches_roots_ = false; 1727 } 1728 } 1729 VisitClassRoots(callback, arg, flags); 1730 array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal); 1731 DCHECK(!array_iftable_.IsNull()); 1732 for (size_t i = 0; i < kFindArrayCacheSize; ++i) { 1733 if (!find_array_class_cache_[i].IsNull()) { 1734 find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal); 1735 } 1736 } 1737} 1738 1739void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) { 1740 if (dex_cache_image_class_lookup_required_) { 1741 MoveImageClassesToClassTable(); 1742 } 1743 // TODO: why isn't this a ReaderMutexLock? 1744 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 1745 for (GcRoot<mirror::Class>& root : class_table_) { 1746 if (!visitor(root.Read(), arg)) { 1747 return; 1748 } 1749 } 1750 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) { 1751 if (!visitor(root.Read(), arg)) { 1752 return; 1753 } 1754 } 1755} 1756 1757static bool GetClassesVisitorSet(mirror::Class* c, void* arg) { 1758 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg); 1759 classes->insert(c); 1760 return true; 1761} 1762 1763struct GetClassesVisitorArrayArg { 1764 Handle<mirror::ObjectArray<mirror::Class>>* classes; 1765 int32_t index; 1766 bool success; 1767}; 1768 1769static bool GetClassesVisitorArray(mirror::Class* c, void* varg) 1770 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 1771 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg); 1772 if (arg->index < (*arg->classes)->GetLength()) { 1773 (*arg->classes)->Set(arg->index, c); 1774 arg->index++; 1775 return true; 1776 } else { 1777 arg->success = false; 1778 return false; 1779 } 1780} 1781 1782void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) { 1783 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem 1784 // is avoiding duplicates. 1785 if (!kMovingClasses) { 1786 std::set<mirror::Class*> classes; 1787 VisitClasses(GetClassesVisitorSet, &classes); 1788 for (mirror::Class* klass : classes) { 1789 if (!visitor(klass, arg)) { 1790 return; 1791 } 1792 } 1793 } else { 1794 Thread* self = Thread::Current(); 1795 StackHandleScope<1> hs(self); 1796 Handle<mirror::ObjectArray<mirror::Class>> classes = 1797 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr); 1798 GetClassesVisitorArrayArg local_arg; 1799 local_arg.classes = &classes; 1800 local_arg.success = false; 1801 // We size the array assuming classes won't be added to the class table during the visit. 1802 // If this assumption fails we iterate again. 1803 while (!local_arg.success) { 1804 size_t class_table_size; 1805 { 1806 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 1807 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size(); 1808 } 1809 mirror::Class* class_type = mirror::Class::GetJavaLangClass(); 1810 mirror::Class* array_of_class = FindArrayClass(self, &class_type); 1811 classes.Assign( 1812 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size)); 1813 CHECK(classes.Get() != nullptr); // OOME. 1814 local_arg.index = 0; 1815 local_arg.success = true; 1816 VisitClasses(GetClassesVisitorArray, &local_arg); 1817 } 1818 for (int32_t i = 0; i < classes->GetLength(); ++i) { 1819 // If the class table shrank during creation of the clases array we expect null elements. If 1820 // the class table grew then the loop repeats. If classes are created after the loop has 1821 // finished then we don't visit. 1822 mirror::Class* klass = classes->Get(i); 1823 if (klass != nullptr && !visitor(klass, arg)) { 1824 return; 1825 } 1826 } 1827 } 1828} 1829 1830ClassLinker::~ClassLinker() { 1831 mirror::Class::ResetClass(); 1832 mirror::String::ResetClass(); 1833 mirror::Reference::ResetClass(); 1834 mirror::ArtField::ResetClass(); 1835 mirror::ArtMethod::ResetClass(); 1836 mirror::BooleanArray::ResetArrayClass(); 1837 mirror::ByteArray::ResetArrayClass(); 1838 mirror::CharArray::ResetArrayClass(); 1839 mirror::DoubleArray::ResetArrayClass(); 1840 mirror::FloatArray::ResetArrayClass(); 1841 mirror::IntArray::ResetArrayClass(); 1842 mirror::LongArray::ResetArrayClass(); 1843 mirror::ShortArray::ResetArrayClass(); 1844 mirror::Throwable::ResetClass(); 1845 mirror::StackTraceElement::ResetClass(); 1846 STLDeleteElements(&boot_class_path_); 1847 STLDeleteElements(&oat_files_); 1848} 1849 1850mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) { 1851 gc::Heap* heap = Runtime::Current()->GetHeap(); 1852 StackHandleScope<16> hs(self); 1853 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache))); 1854 Handle<mirror::DexCache> dex_cache( 1855 hs.NewHandle(down_cast<mirror::DexCache*>( 1856 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(), 1857 VoidFunctor())))); 1858 if (dex_cache.Get() == nullptr) { 1859 return nullptr; 1860 } 1861 Handle<mirror::String> 1862 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str()))); 1863 if (location.Get() == nullptr) { 1864 return nullptr; 1865 } 1866 Handle<mirror::ObjectArray<mirror::String>> 1867 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds()))); 1868 if (strings.Get() == nullptr) { 1869 return nullptr; 1870 } 1871 Handle<mirror::ObjectArray<mirror::Class>> 1872 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds()))); 1873 if (types.Get() == nullptr) { 1874 return nullptr; 1875 } 1876 Handle<mirror::ObjectArray<mirror::ArtMethod>> 1877 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds()))); 1878 if (methods.Get() == nullptr) { 1879 return nullptr; 1880 } 1881 Handle<mirror::ObjectArray<mirror::ArtField>> 1882 fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds()))); 1883 if (fields.Get() == nullptr) { 1884 return nullptr; 1885 } 1886 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(), 1887 fields.Get()); 1888 return dex_cache.Get(); 1889} 1890 1891mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class, 1892 uint32_t class_size) { 1893 DCHECK_GE(class_size, sizeof(mirror::Class)); 1894 gc::Heap* heap = Runtime::Current()->GetHeap(); 1895 mirror::Class::InitializeClassVisitor visitor(class_size); 1896 mirror::Object* k = kMovingClasses ? 1897 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) : 1898 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor); 1899 if (UNLIKELY(k == nullptr)) { 1900 CHECK(self->IsExceptionPending()); // OOME. 1901 return nullptr; 1902 } 1903 return k->AsClass(); 1904} 1905 1906mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) { 1907 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size); 1908} 1909 1910mirror::ArtField* ClassLinker::AllocArtField(Thread* self) { 1911 return down_cast<mirror::ArtField*>( 1912 GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self)); 1913} 1914 1915mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) { 1916 return down_cast<mirror::ArtMethod*>( 1917 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self)); 1918} 1919 1920mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray( 1921 Thread* self, size_t length) { 1922 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc( 1923 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length); 1924} 1925 1926mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor, 1927 mirror::Class* klass) { 1928 DCHECK(klass != nullptr); 1929 1930 // For temporary classes we must wait for them to be retired. 1931 if (init_done_ && klass->IsTemp()) { 1932 CHECK(!klass->IsResolved()); 1933 if (klass->IsErroneous()) { 1934 ThrowEarlierClassFailure(klass); 1935 return nullptr; 1936 } 1937 StackHandleScope<1> hs(self); 1938 Handle<mirror::Class> h_class(hs.NewHandle(klass)); 1939 ObjectLock<mirror::Class> lock(self, h_class); 1940 // Loop and wait for the resolving thread to retire this class. 1941 while (!h_class->IsRetired() && !h_class->IsErroneous()) { 1942 lock.WaitIgnoringInterrupts(); 1943 } 1944 if (h_class->IsErroneous()) { 1945 ThrowEarlierClassFailure(h_class.Get()); 1946 return nullptr; 1947 } 1948 CHECK(h_class->IsRetired()); 1949 // Get the updated class from class table. 1950 klass = LookupClass(descriptor, ComputeModifiedUtf8Hash(descriptor), 1951 h_class.Get()->GetClassLoader()); 1952 } 1953 1954 // Wait for the class if it has not already been linked. 1955 if (!klass->IsResolved() && !klass->IsErroneous()) { 1956 StackHandleScope<1> hs(self); 1957 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass)); 1958 ObjectLock<mirror::Class> lock(self, h_class); 1959 // Check for circular dependencies between classes. 1960 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) { 1961 ThrowClassCircularityError(h_class.Get()); 1962 h_class->SetStatus(mirror::Class::kStatusError, self); 1963 return nullptr; 1964 } 1965 // Wait for the pending initialization to complete. 1966 while (!h_class->IsResolved() && !h_class->IsErroneous()) { 1967 lock.WaitIgnoringInterrupts(); 1968 } 1969 } 1970 1971 if (klass->IsErroneous()) { 1972 ThrowEarlierClassFailure(klass); 1973 return nullptr; 1974 } 1975 // Return the loaded class. No exceptions should be pending. 1976 CHECK(klass->IsResolved()) << PrettyClass(klass); 1977 self->AssertNoPendingException(); 1978 return klass; 1979} 1980 1981typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry; 1982 1983// Search a collection of DexFiles for a descriptor 1984ClassPathEntry FindInClassPath(const char* descriptor, 1985 size_t hash, const std::vector<const DexFile*>& class_path) { 1986 for (const DexFile* dex_file : class_path) { 1987 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash); 1988 if (dex_class_def != nullptr) { 1989 return ClassPathEntry(dex_file, dex_class_def); 1990 } 1991 } 1992 return ClassPathEntry(nullptr, nullptr); 1993} 1994 1995mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa, 1996 Thread* self, const char* descriptor, 1997 size_t hash, 1998 Handle<mirror::ClassLoader> class_loader) { 1999 if (class_loader->GetClass() != 2000 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) || 2001 class_loader->GetParent()->GetClass() != 2002 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) { 2003 return nullptr; 2004 } 2005 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_); 2006 // Check if this would be found in the parent boot class loader. 2007 if (pair.second != nullptr) { 2008 mirror::Class* klass = LookupClass(descriptor, hash, nullptr); 2009 if (klass != nullptr) { 2010 return EnsureResolved(self, descriptor, klass); 2011 } 2012 klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first, 2013 *pair.second); 2014 if (klass != nullptr) { 2015 return klass; 2016 } 2017 CHECK(self->IsExceptionPending()) << descriptor; 2018 self->ClearException(); 2019 } else { 2020 // RegisterDexFile may allocate dex caches (and cause thread suspension). 2021 StackHandleScope<3> hs(self); 2022 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader. 2023 // We need to get the DexPathList and loop through it. 2024 Handle<mirror::ArtField> cookie_field = 2025 hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie)); 2026 Handle<mirror::ArtField> dex_file_field = 2027 hs.NewHandle( 2028 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList$Element_dexFile)); 2029 mirror::Object* dex_path_list = 2030 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)-> 2031 GetObject(class_loader.Get()); 2032 if (dex_path_list != nullptr && dex_file_field.Get() != nullptr && 2033 cookie_field.Get() != nullptr) { 2034 // DexPathList has an array dexElements of Elements[] which each contain a dex file. 2035 mirror::Object* dex_elements_obj = 2036 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)-> 2037 GetObject(dex_path_list); 2038 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look 2039 // at the mCookie which is a DexFile vector. 2040 if (dex_elements_obj != nullptr) { 2041 Handle<mirror::ObjectArray<mirror::Object>> dex_elements = 2042 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()); 2043 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) { 2044 mirror::Object* element = dex_elements->GetWithoutChecks(i); 2045 if (element == nullptr) { 2046 // Should never happen, fall back to java code to throw a NPE. 2047 break; 2048 } 2049 mirror::Object* dex_file = dex_file_field->GetObject(element); 2050 if (dex_file != nullptr) { 2051 const uint64_t cookie = cookie_field->GetLong(dex_file); 2052 auto* dex_files = 2053 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie)); 2054 if (dex_files == nullptr) { 2055 // This should never happen so log a warning. 2056 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor; 2057 break; 2058 } 2059 for (const DexFile* dex_file : *dex_files) { 2060 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash); 2061 if (dex_class_def != nullptr) { 2062 RegisterDexFile(*dex_file); 2063 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader, *dex_file, 2064 *dex_class_def); 2065 if (klass == nullptr) { 2066 CHECK(self->IsExceptionPending()) << descriptor; 2067 self->ClearException(); 2068 return nullptr; 2069 } 2070 return klass; 2071 } 2072 } 2073 } 2074 } 2075 } 2076 } 2077 } 2078 return nullptr; 2079} 2080 2081mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor, 2082 Handle<mirror::ClassLoader> class_loader) { 2083 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string"; 2084 DCHECK(self != nullptr); 2085 self->AssertNoPendingException(); 2086 if (descriptor[1] == '\0') { 2087 // only the descriptors of primitive types should be 1 character long, also avoid class lookup 2088 // for primitive classes that aren't backed by dex files. 2089 return FindPrimitiveClass(descriptor[0]); 2090 } 2091 const size_t hash = ComputeModifiedUtf8Hash(descriptor); 2092 // Find the class in the loaded classes table. 2093 mirror::Class* klass = LookupClass(descriptor, hash, class_loader.Get()); 2094 if (klass != nullptr) { 2095 return EnsureResolved(self, descriptor, klass); 2096 } 2097 // Class is not yet loaded. 2098 if (descriptor[0] == '[') { 2099 return CreateArrayClass(self, descriptor, hash, class_loader); 2100 } else if (class_loader.Get() == nullptr) { 2101 // The boot class loader, search the boot class path. 2102 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_); 2103 if (pair.second != nullptr) { 2104 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first, 2105 *pair.second); 2106 } else { 2107 // The boot class loader is searched ahead of the application class loader, failures are 2108 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to 2109 // trigger the chaining with a proper stack trace. 2110 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError(); 2111 self->SetException(ThrowLocation(), pre_allocated); 2112 return nullptr; 2113 } 2114 } else if (Runtime::Current()->UseCompileTimeClassPath()) { 2115 // First try with the bootstrap class loader. 2116 if (class_loader.Get() != nullptr) { 2117 klass = LookupClass(descriptor, hash, nullptr); 2118 if (klass != nullptr) { 2119 return EnsureResolved(self, descriptor, klass); 2120 } 2121 } 2122 // If the lookup failed search the boot class path. We don't perform a recursive call to avoid 2123 // a NoClassDefFoundError being allocated. 2124 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_); 2125 if (pair.second != nullptr) { 2126 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first, 2127 *pair.second); 2128 } 2129 // Next try the compile time class path. 2130 const std::vector<const DexFile*>* class_path; 2131 { 2132 ScopedObjectAccessUnchecked soa(self); 2133 ScopedLocalRef<jobject> jclass_loader(soa.Env(), 2134 soa.AddLocalReference<jobject>(class_loader.Get())); 2135 class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get()); 2136 } 2137 pair = FindInClassPath(descriptor, hash, *class_path); 2138 if (pair.second != nullptr) { 2139 return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second); 2140 } 2141 } else { 2142 ScopedObjectAccessUnchecked soa(self); 2143 mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader); 2144 if (klass != nullptr) { 2145 return klass; 2146 } 2147 ScopedLocalRef<jobject> class_loader_object(soa.Env(), 2148 soa.AddLocalReference<jobject>(class_loader.Get())); 2149 std::string class_name_string(DescriptorToDot(descriptor)); 2150 ScopedLocalRef<jobject> result(soa.Env(), nullptr); 2151 { 2152 ScopedThreadStateChange tsc(self, kNative); 2153 ScopedLocalRef<jobject> class_name_object(soa.Env(), 2154 soa.Env()->NewStringUTF(class_name_string.c_str())); 2155 if (class_name_object.get() == nullptr) { 2156 DCHECK(self->IsExceptionPending()); // OOME. 2157 return nullptr; 2158 } 2159 CHECK(class_loader_object.get() != nullptr); 2160 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(), 2161 WellKnownClasses::java_lang_ClassLoader_loadClass, 2162 class_name_object.get())); 2163 } 2164 if (self->IsExceptionPending()) { 2165 // If the ClassLoader threw, pass that exception up. 2166 return nullptr; 2167 } else if (result.get() == nullptr) { 2168 // broken loader - throw NPE to be compatible with Dalvik 2169 ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s", 2170 class_name_string.c_str()).c_str()); 2171 return nullptr; 2172 } else { 2173 // success, return mirror::Class* 2174 return soa.Decode<mirror::Class*>(result.get()); 2175 } 2176 } 2177 2178 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str()); 2179 return nullptr; 2180} 2181 2182mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash, 2183 Handle<mirror::ClassLoader> class_loader, 2184 const DexFile& dex_file, 2185 const DexFile::ClassDef& dex_class_def) { 2186 StackHandleScope<3> hs(self); 2187 auto klass = hs.NewHandle<mirror::Class>(nullptr); 2188 2189 // Load the class from the dex file. 2190 if (UNLIKELY(!init_done_)) { 2191 // finish up init of hand crafted class_roots_ 2192 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) { 2193 klass.Assign(GetClassRoot(kJavaLangObject)); 2194 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) { 2195 klass.Assign(GetClassRoot(kJavaLangClass)); 2196 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) { 2197 klass.Assign(GetClassRoot(kJavaLangString)); 2198 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) { 2199 klass.Assign(GetClassRoot(kJavaLangRefReference)); 2200 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) { 2201 klass.Assign(GetClassRoot(kJavaLangDexCache)); 2202 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) { 2203 klass.Assign(GetClassRoot(kJavaLangReflectArtField)); 2204 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) { 2205 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod)); 2206 } 2207 } 2208 2209 if (klass.Get() == nullptr) { 2210 // Allocate a class with the status of not ready. 2211 // Interface object should get the right size here. Regular class will 2212 // figure out the right size later and be replaced with one of the right 2213 // size when the class becomes resolved. 2214 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def))); 2215 } 2216 if (UNLIKELY(klass.Get() == nullptr)) { 2217 CHECK(self->IsExceptionPending()); // Expect an OOME. 2218 return nullptr; 2219 } 2220 klass->SetDexCache(FindDexCache(dex_file)); 2221 LoadClass(dex_file, dex_class_def, klass, class_loader.Get()); 2222 ObjectLock<mirror::Class> lock(self, klass); 2223 if (self->IsExceptionPending()) { 2224 // An exception occured during load, set status to erroneous while holding klass' lock in case 2225 // notification is necessary. 2226 if (!klass->IsErroneous()) { 2227 klass->SetStatus(mirror::Class::kStatusError, self); 2228 } 2229 return nullptr; 2230 } 2231 klass->SetClinitThreadId(self->GetTid()); 2232 2233 // Add the newly loaded class to the loaded classes table. 2234 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash); 2235 if (existing != nullptr) { 2236 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause 2237 // this thread to block. 2238 return EnsureResolved(self, descriptor, existing); 2239 } 2240 2241 // Finish loading (if necessary) by finding parents 2242 CHECK(!klass->IsLoaded()); 2243 if (!LoadSuperAndInterfaces(klass, dex_file)) { 2244 // Loading failed. 2245 if (!klass->IsErroneous()) { 2246 klass->SetStatus(mirror::Class::kStatusError, self); 2247 } 2248 return nullptr; 2249 } 2250 CHECK(klass->IsLoaded()); 2251 // Link the class (if necessary) 2252 CHECK(!klass->IsResolved()); 2253 // TODO: Use fast jobjects? 2254 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr); 2255 2256 mirror::Class* new_class = nullptr; 2257 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) { 2258 // Linking failed. 2259 if (!klass->IsErroneous()) { 2260 klass->SetStatus(mirror::Class::kStatusError, self); 2261 } 2262 return nullptr; 2263 } 2264 self->AssertNoPendingException(); 2265 CHECK(new_class != nullptr) << descriptor; 2266 CHECK(new_class->IsResolved()) << descriptor; 2267 2268 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class)); 2269 2270 /* 2271 * We send CLASS_PREPARE events to the debugger from here. The 2272 * definition of "preparation" is creating the static fields for a 2273 * class and initializing them to the standard default values, but not 2274 * executing any code (that comes later, during "initialization"). 2275 * 2276 * We did the static preparation in LinkClass. 2277 * 2278 * The class has been prepared and resolved but possibly not yet verified 2279 * at this point. 2280 */ 2281 Dbg::PostClassPrepare(new_class_h.Get()); 2282 2283 return new_class_h.Get(); 2284} 2285 2286uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file, 2287 const DexFile::ClassDef& dex_class_def) { 2288 const byte* class_data = dex_file.GetClassData(dex_class_def); 2289 size_t num_ref = 0; 2290 size_t num_32 = 0; 2291 size_t num_64 = 0; 2292 if (class_data != nullptr) { 2293 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) { 2294 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex()); 2295 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id); 2296 char c = descriptor[0]; 2297 if (c == 'L' || c == '[') { 2298 num_ref++; 2299 } else if (c == 'J' || c == 'D') { 2300 num_64++; 2301 } else { 2302 num_32++; 2303 } 2304 } 2305 } 2306 return mirror::Class::ComputeClassSize(false, 0, num_32, num_64, num_ref); 2307} 2308 2309bool ClassLinker::FindOatClass(const DexFile& dex_file, 2310 uint16_t class_def_idx, 2311 OatFile::OatClass* oat_class) { 2312 DCHECK(oat_class != nullptr); 2313 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16); 2314 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file); 2315 if (oat_dex_file == nullptr) { 2316 return false; 2317 } 2318 *oat_class = oat_dex_file->GetOatClass(class_def_idx); 2319 return true; 2320} 2321 2322static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx, 2323 uint32_t method_idx) { 2324 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx); 2325 const byte* class_data = dex_file.GetClassData(class_def); 2326 CHECK(class_data != nullptr); 2327 ClassDataItemIterator it(dex_file, class_data); 2328 // Skip fields 2329 while (it.HasNextStaticField()) { 2330 it.Next(); 2331 } 2332 while (it.HasNextInstanceField()) { 2333 it.Next(); 2334 } 2335 // Process methods 2336 size_t class_def_method_index = 0; 2337 while (it.HasNextDirectMethod()) { 2338 if (it.GetMemberIndex() == method_idx) { 2339 return class_def_method_index; 2340 } 2341 class_def_method_index++; 2342 it.Next(); 2343 } 2344 while (it.HasNextVirtualMethod()) { 2345 if (it.GetMemberIndex() == method_idx) { 2346 return class_def_method_index; 2347 } 2348 class_def_method_index++; 2349 it.Next(); 2350 } 2351 DCHECK(!it.HasNext()); 2352 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation(); 2353 return 0; 2354} 2355 2356bool ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, OatFile::OatMethod* oat_method) { 2357 DCHECK(oat_method != nullptr); 2358 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution 2359 // method for direct methods (or virtual methods made direct). 2360 mirror::Class* declaring_class = method->GetDeclaringClass(); 2361 size_t oat_method_index; 2362 if (method->IsStatic() || method->IsDirect()) { 2363 // Simple case where the oat method index was stashed at load time. 2364 oat_method_index = method->GetMethodIndex(); 2365 } else { 2366 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index 2367 // by search for its position in the declared virtual methods. 2368 oat_method_index = declaring_class->NumDirectMethods(); 2369 size_t end = declaring_class->NumVirtualMethods(); 2370 bool found = false; 2371 for (size_t i = 0; i < end; i++) { 2372 // Check method index instead of identity in case of duplicate method definitions. 2373 if (method->GetDexMethodIndex() == 2374 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) { 2375 found = true; 2376 break; 2377 } 2378 oat_method_index++; 2379 } 2380 CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method); 2381 } 2382 DCHECK_EQ(oat_method_index, 2383 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(), 2384 method->GetDeclaringClass()->GetDexClassDefIndex(), 2385 method->GetDexMethodIndex())); 2386 OatFile::OatClass oat_class; 2387 if (!FindOatClass(*declaring_class->GetDexCache()->GetDexFile(), 2388 declaring_class->GetDexClassDefIndex(), 2389 &oat_class)) { 2390 return false; 2391 } 2392 2393 *oat_method = oat_class.GetOatMethod(oat_method_index); 2394 return true; 2395} 2396 2397// Special case to get oat code without overwriting a trampoline. 2398const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) { 2399 CHECK(!method->IsAbstract()) << PrettyMethod(method); 2400 if (method->IsProxyMethod()) { 2401 return GetQuickProxyInvokeHandler(); 2402 } 2403 OatFile::OatMethod oat_method; 2404 const void* result = nullptr; 2405 if (FindOatMethodFor(method, &oat_method)) { 2406 result = oat_method.GetQuickCode(); 2407 } 2408 2409 if (result == nullptr) { 2410 if (method->IsNative()) { 2411 // No code and native? Use generic trampoline. 2412 result = GetQuickGenericJniTrampoline(); 2413#if defined(ART_USE_PORTABLE_COMPILER) 2414 } else if (method->IsPortableCompiled()) { 2415 // No code? Do we expect portable code? 2416 result = GetQuickToPortableBridge(); 2417#endif 2418 } else { 2419 // No code? You must mean to go into the interpreter. 2420 result = GetQuickToInterpreterBridge(); 2421 } 2422 } 2423 return result; 2424} 2425 2426#if defined(ART_USE_PORTABLE_COMPILER) 2427const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method, 2428 bool* have_portable_code) { 2429 CHECK(!method->IsAbstract()) << PrettyMethod(method); 2430 *have_portable_code = false; 2431 if (method->IsProxyMethod()) { 2432 return GetPortableProxyInvokeHandler(); 2433 } 2434 OatFile::OatMethod oat_method; 2435 const void* result = nullptr; 2436 const void* quick_code = nullptr; 2437 if (FindOatMethodFor(method, &oat_method)) { 2438 result = oat_method.GetPortableCode(); 2439 quick_code = oat_method.GetQuickCode(); 2440 } 2441 2442 if (result == nullptr) { 2443 if (quick_code == nullptr) { 2444 // No code? You must mean to go into the interpreter. 2445 result = GetPortableToInterpreterBridge(); 2446 } else { 2447 // No code? But there's quick code, so use a bridge. 2448 result = GetPortableToQuickBridge(); 2449 } 2450 } else { 2451 *have_portable_code = true; 2452 } 2453 return result; 2454} 2455#endif 2456 2457const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx, 2458 uint32_t method_idx) { 2459 OatFile::OatClass oat_class; 2460 if (!FindOatClass(dex_file, class_def_idx, &oat_class)) { 2461 return nullptr; 2462 } 2463 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx); 2464 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode(); 2465} 2466 2467#if defined(ART_USE_PORTABLE_COMPILER) 2468const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx, 2469 uint32_t method_idx) { 2470 OatFile::OatClass oat_class; 2471 if (!FindOatClass(dex_file, class_def_idx, &oat_class)) { 2472 return nullptr; 2473 } 2474 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx); 2475 return oat_class.GetOatMethod(oat_method_idx).GetPortableCode(); 2476} 2477#endif 2478 2479// Returns true if the method must run with interpreter, false otherwise. 2480static bool NeedsInterpreter( 2481 mirror::ArtMethod* method, const void* quick_code, const void* portable_code) 2482 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 2483 if ((quick_code == nullptr) && (portable_code == nullptr)) { 2484 // No code: need interpreter. 2485 // May return true for native code, in the case of generic JNI 2486 // DCHECK(!method->IsNative()); 2487 return true; 2488 } 2489#ifdef ART_SEA_IR_MODE 2490 ScopedObjectAccess soa(Thread::Current()); 2491 if (std::string::npos != PrettyMethod(method).find("fibonacci")) { 2492 LOG(INFO) << "Found " << PrettyMethod(method); 2493 return false; 2494 } 2495#endif 2496 // If interpreter mode is enabled, every method (except native and proxy) must 2497 // be run with interpreter. 2498 return Runtime::Current()->GetInstrumentation()->InterpretOnly() && 2499 !method->IsNative() && !method->IsProxyMethod(); 2500} 2501 2502void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) { 2503 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass); 2504 if (klass->NumDirectMethods() == 0) { 2505 return; // No direct methods => no static methods. 2506 } 2507 Runtime* runtime = Runtime::Current(); 2508 if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) { 2509 if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) { 2510 return; // OAT file unavailable. 2511 } 2512 } 2513 2514 const DexFile& dex_file = klass->GetDexFile(); 2515 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 2516 CHECK(dex_class_def != nullptr); 2517 const byte* class_data = dex_file.GetClassData(*dex_class_def); 2518 // There should always be class data if there were direct methods. 2519 CHECK(class_data != nullptr) << PrettyDescriptor(klass); 2520 ClassDataItemIterator it(dex_file, class_data); 2521 // Skip fields 2522 while (it.HasNextStaticField()) { 2523 it.Next(); 2524 } 2525 while (it.HasNextInstanceField()) { 2526 it.Next(); 2527 } 2528 OatFile::OatClass oat_class; 2529 bool has_oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(), &oat_class); 2530 // Link the code of methods skipped by LinkCode. 2531 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) { 2532 mirror::ArtMethod* method = klass->GetDirectMethod(method_index); 2533 if (!method->IsStatic()) { 2534 // Only update static methods. 2535 continue; 2536 } 2537 const void* portable_code = nullptr; 2538 const void* quick_code = nullptr; 2539 if (has_oat_class) { 2540 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index); 2541 portable_code = oat_method.GetPortableCode(); 2542 quick_code = oat_method.GetQuickCode(); 2543 } 2544 const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code); 2545 bool have_portable_code = false; 2546 if (enter_interpreter) { 2547 // Use interpreter entry point. 2548 // Check whether the method is native, in which case it's generic JNI. 2549 if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) { 2550 quick_code = GetQuickGenericJniTrampoline(); 2551#if defined(ART_USE_PORTABLE_COMPILER) 2552 portable_code = GetPortableToQuickBridge(); 2553#endif 2554 } else { 2555#if defined(ART_USE_PORTABLE_COMPILER) 2556 portable_code = GetPortableToInterpreterBridge(); 2557#endif 2558 quick_code = GetQuickToInterpreterBridge(); 2559 } 2560 } else { 2561#if defined(ART_USE_PORTABLE_COMPILER) 2562 if (portable_code == nullptr) { 2563 portable_code = GetPortableToQuickBridge(); 2564 } else { 2565 have_portable_code = true; 2566 } 2567 if (quick_code == nullptr) { 2568 quick_code = GetQuickToPortableBridge(); 2569 } 2570#else 2571 if (quick_code == nullptr) { 2572 quick_code = GetQuickToInterpreterBridge(); 2573 } 2574#endif 2575 } 2576 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code, 2577 have_portable_code); 2578 } 2579 // Ignore virtual methods on the iterator. 2580} 2581 2582void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method, const OatFile::OatClass* oat_class, 2583 const DexFile& dex_file, uint32_t dex_method_index, 2584 uint32_t method_index) { 2585 if (Runtime::Current()->IsCompiler()) { 2586 // The following code only applies to a non-compiler runtime. 2587 return; 2588 } 2589 // Method shouldn't have already been linked. 2590 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr); 2591#if defined(ART_USE_PORTABLE_COMPILER) 2592 DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr); 2593#endif 2594 if (oat_class != nullptr) { 2595 // Every kind of method should at least get an invoke stub from the oat_method. 2596 // non-abstract methods also get their code pointers. 2597 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index); 2598 oat_method.LinkMethod(method.Get()); 2599 } 2600 2601 // Install entry point from interpreter. 2602 bool enter_interpreter = NeedsInterpreter(method.Get(), 2603 method->GetEntryPointFromQuickCompiledCode(), 2604#if defined(ART_USE_PORTABLE_COMPILER) 2605 method->GetEntryPointFromPortableCompiledCode()); 2606#else 2607 nullptr); 2608#endif 2609 if (enter_interpreter && !method->IsNative()) { 2610 method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge); 2611 } else { 2612 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge); 2613 } 2614 2615 if (method->IsAbstract()) { 2616 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge()); 2617#if defined(ART_USE_PORTABLE_COMPILER) 2618 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge()); 2619#endif 2620 return; 2621 } 2622 2623 bool have_portable_code = false; 2624 if (method->IsStatic() && !method->IsConstructor()) { 2625 // For static methods excluding the class initializer, install the trampoline. 2626 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines 2627 // after initializing class (see ClassLinker::InitializeClass method). 2628 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline()); 2629#if defined(ART_USE_PORTABLE_COMPILER) 2630 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline()); 2631#endif 2632 } else if (enter_interpreter) { 2633 if (!method->IsNative()) { 2634 // Set entry point from compiled code if there's no code or in interpreter only mode. 2635 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge()); 2636#if defined(ART_USE_PORTABLE_COMPILER) 2637 method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge()); 2638#endif 2639 } else { 2640 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline()); 2641#if defined(ART_USE_PORTABLE_COMPILER) 2642 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge()); 2643#endif 2644 } 2645#if defined(ART_USE_PORTABLE_COMPILER) 2646 } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) { 2647 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr); 2648 have_portable_code = true; 2649 method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge()); 2650#endif 2651 } else { 2652 DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr); 2653#if defined(ART_USE_PORTABLE_COMPILER) 2654 method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge()); 2655#endif 2656 } 2657 2658 if (method->IsNative()) { 2659 // Unregistering restores the dlsym lookup stub. 2660 method->UnregisterNative(Thread::Current()); 2661 2662 if (enter_interpreter) { 2663 // We have a native method here without code. Then it should have either the GenericJni 2664 // trampoline as entrypoint (non-static), or the Resolution trampoline (static). 2665 DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline() 2666 || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline()); 2667 } 2668 } 2669 2670 // Allow instrumentation its chance to hijack code. 2671 Runtime* runtime = Runtime::Current(); 2672 runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(), 2673 method->GetEntryPointFromQuickCompiledCode(), 2674#if defined(ART_USE_PORTABLE_COMPILER) 2675 method->GetEntryPointFromPortableCompiledCode(), 2676#else 2677 nullptr, 2678#endif 2679 have_portable_code); 2680} 2681 2682void ClassLinker::LoadClass(const DexFile& dex_file, 2683 const DexFile::ClassDef& dex_class_def, 2684 Handle<mirror::Class> klass, 2685 mirror::ClassLoader* class_loader) { 2686 CHECK(klass.Get() != nullptr); 2687 CHECK(klass->GetDexCache() != nullptr); 2688 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus()); 2689 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def); 2690 CHECK(descriptor != nullptr); 2691 2692 klass->SetClass(GetClassRoot(kJavaLangClass)); 2693 if (kUseBakerOrBrooksReadBarrier) { 2694 klass->AssertReadBarrierPointer(); 2695 } 2696 uint32_t access_flags = dex_class_def.GetJavaAccessFlags(); 2697 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U); 2698 klass->SetAccessFlags(access_flags); 2699 klass->SetClassLoader(class_loader); 2700 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 2701 klass->SetStatus(mirror::Class::kStatusIdx, nullptr); 2702 2703 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def)); 2704 klass->SetDexTypeIndex(dex_class_def.class_idx_); 2705 2706 const byte* class_data = dex_file.GetClassData(dex_class_def); 2707 if (class_data == nullptr) { 2708 return; // no fields or methods - for example a marker interface 2709 } 2710 2711 OatFile::OatClass oat_class; 2712 if (Runtime::Current()->IsStarted() 2713 && !Runtime::Current()->UseCompileTimeClassPath() 2714 && FindOatClass(dex_file, klass->GetDexClassDefIndex(), &oat_class)) { 2715 LoadClassMembers(dex_file, class_data, klass, class_loader, &oat_class); 2716 } else { 2717 LoadClassMembers(dex_file, class_data, klass, class_loader, nullptr); 2718 } 2719} 2720 2721void ClassLinker::LoadClassMembers(const DexFile& dex_file, 2722 const byte* class_data, 2723 Handle<mirror::Class> klass, 2724 mirror::ClassLoader* class_loader, 2725 const OatFile::OatClass* oat_class) { 2726 // Load fields. 2727 ClassDataItemIterator it(dex_file, class_data); 2728 Thread* self = Thread::Current(); 2729 if (it.NumStaticFields() != 0) { 2730 mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields()); 2731 if (UNLIKELY(statics == nullptr)) { 2732 CHECK(self->IsExceptionPending()); // OOME. 2733 return; 2734 } 2735 klass->SetSFields(statics); 2736 } 2737 if (it.NumInstanceFields() != 0) { 2738 mirror::ObjectArray<mirror::ArtField>* fields = 2739 AllocArtFieldArray(self, it.NumInstanceFields()); 2740 if (UNLIKELY(fields == nullptr)) { 2741 CHECK(self->IsExceptionPending()); // OOME. 2742 return; 2743 } 2744 klass->SetIFields(fields); 2745 } 2746 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) { 2747 StackHandleScope<1> hs(self); 2748 Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self))); 2749 if (UNLIKELY(sfield.Get() == nullptr)) { 2750 CHECK(self->IsExceptionPending()); // OOME. 2751 return; 2752 } 2753 klass->SetStaticField(i, sfield.Get()); 2754 LoadField(dex_file, it, klass, sfield); 2755 } 2756 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) { 2757 StackHandleScope<1> hs(self); 2758 Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self))); 2759 if (UNLIKELY(ifield.Get() == nullptr)) { 2760 CHECK(self->IsExceptionPending()); // OOME. 2761 return; 2762 } 2763 klass->SetInstanceField(i, ifield.Get()); 2764 LoadField(dex_file, it, klass, ifield); 2765 } 2766 2767 // Load methods. 2768 if (it.NumDirectMethods() != 0) { 2769 // TODO: append direct methods to class object 2770 mirror::ObjectArray<mirror::ArtMethod>* directs = 2771 AllocArtMethodArray(self, it.NumDirectMethods()); 2772 if (UNLIKELY(directs == nullptr)) { 2773 CHECK(self->IsExceptionPending()); // OOME. 2774 return; 2775 } 2776 klass->SetDirectMethods(directs); 2777 } 2778 if (it.NumVirtualMethods() != 0) { 2779 // TODO: append direct methods to class object 2780 mirror::ObjectArray<mirror::ArtMethod>* virtuals = 2781 AllocArtMethodArray(self, it.NumVirtualMethods()); 2782 if (UNLIKELY(virtuals == nullptr)) { 2783 CHECK(self->IsExceptionPending()); // OOME. 2784 return; 2785 } 2786 klass->SetVirtualMethods(virtuals); 2787 } 2788 size_t class_def_method_index = 0; 2789 uint32_t last_dex_method_index = DexFile::kDexNoIndex; 2790 size_t last_class_def_method_index = 0; 2791 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) { 2792 StackHandleScope<1> hs(self); 2793 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass))); 2794 if (UNLIKELY(method.Get() == nullptr)) { 2795 CHECK(self->IsExceptionPending()); // OOME. 2796 return; 2797 } 2798 klass->SetDirectMethod(i, method.Get()); 2799 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index); 2800 uint32_t it_method_index = it.GetMemberIndex(); 2801 if (last_dex_method_index == it_method_index) { 2802 // duplicate case 2803 method->SetMethodIndex(last_class_def_method_index); 2804 } else { 2805 method->SetMethodIndex(class_def_method_index); 2806 last_dex_method_index = it_method_index; 2807 last_class_def_method_index = class_def_method_index; 2808 } 2809 class_def_method_index++; 2810 } 2811 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) { 2812 StackHandleScope<1> hs(self); 2813 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass))); 2814 if (UNLIKELY(method.Get() == nullptr)) { 2815 CHECK(self->IsExceptionPending()); // OOME. 2816 return; 2817 } 2818 klass->SetVirtualMethod(i, method.Get()); 2819 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i); 2820 LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index); 2821 class_def_method_index++; 2822 } 2823 DCHECK(!it.HasNext()); 2824} 2825 2826void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it, 2827 Handle<mirror::Class> klass, Handle<mirror::ArtField> dst) { 2828 uint32_t field_idx = it.GetMemberIndex(); 2829 dst->SetDexFieldIndex(field_idx); 2830 dst->SetDeclaringClass(klass.Get()); 2831 dst->SetAccessFlags(it.GetFieldAccessFlags()); 2832} 2833 2834mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file, 2835 const ClassDataItemIterator& it, 2836 Handle<mirror::Class> klass) { 2837 uint32_t dex_method_idx = it.GetMemberIndex(); 2838 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx); 2839 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_); 2840 2841 mirror::ArtMethod* dst = AllocArtMethod(self); 2842 if (UNLIKELY(dst == nullptr)) { 2843 CHECK(self->IsExceptionPending()); // OOME. 2844 return nullptr; 2845 } 2846 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass()); 2847 2848 const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod"); 2849 dst->SetDexMethodIndex(dex_method_idx); 2850 dst->SetDeclaringClass(klass.Get()); 2851 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset()); 2852 2853 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings()); 2854 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods()); 2855 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes()); 2856 2857 uint32_t access_flags = it.GetMethodAccessFlags(); 2858 2859 if (UNLIKELY(strcmp("finalize", method_name) == 0)) { 2860 // Set finalizable flag on declaring class. 2861 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) { 2862 // Void return type. 2863 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged. 2864 klass->SetFinalizable(); 2865 } else { 2866 std::string temp; 2867 const char* klass_descriptor = klass->GetDescriptor(&temp); 2868 // The Enum class declares a "final" finalize() method to prevent subclasses from 2869 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its 2870 // subclasses, so we exclude it here. 2871 // We also want to avoid setting the flag on Object, where we know that finalize() is 2872 // empty. 2873 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 && 2874 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) { 2875 klass->SetFinalizable(); 2876 } 2877 } 2878 } 2879 } else if (method_name[0] == '<') { 2880 // Fix broken access flags for initializers. Bug 11157540. 2881 bool is_init = (strcmp("<init>", method_name) == 0); 2882 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0); 2883 if (UNLIKELY(!is_init && !is_clinit)) { 2884 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name; 2885 } else { 2886 if (UNLIKELY((access_flags & kAccConstructor) == 0)) { 2887 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class " 2888 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation(); 2889 access_flags |= kAccConstructor; 2890 } 2891 } 2892 } 2893 dst->SetAccessFlags(access_flags); 2894 2895 self->EndAssertNoThreadSuspension(old_cause); 2896 return dst; 2897} 2898 2899void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) { 2900 Thread* self = Thread::Current(); 2901 StackHandleScope<1> hs(self); 2902 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file))); 2903 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for " 2904 << dex_file.GetLocation(); 2905 AppendToBootClassPath(dex_file, dex_cache); 2906} 2907 2908void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, 2909 Handle<mirror::DexCache> dex_cache) { 2910 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation(); 2911 boot_class_path_.push_back(&dex_file); 2912 RegisterDexFile(dex_file, dex_cache); 2913} 2914 2915bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) { 2916 dex_lock_.AssertSharedHeld(Thread::Current()); 2917 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2918 mirror::DexCache* dex_cache = GetDexCache(i); 2919 if (dex_cache->GetDexFile() == &dex_file) { 2920 return true; 2921 } 2922 } 2923 return false; 2924} 2925 2926bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) { 2927 ReaderMutexLock mu(Thread::Current(), dex_lock_); 2928 return IsDexFileRegisteredLocked(dex_file); 2929} 2930 2931void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, 2932 Handle<mirror::DexCache> dex_cache) { 2933 dex_lock_.AssertExclusiveHeld(Thread::Current()); 2934 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation(); 2935 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation())) 2936 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation(); 2937 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get())); 2938 dex_cache->SetDexFile(&dex_file); 2939 if (log_new_dex_caches_roots_) { 2940 // TODO: This is not safe if we can remove dex caches. 2941 new_dex_cache_roots_.push_back(dex_caches_.size() - 1); 2942 } 2943} 2944 2945void ClassLinker::RegisterDexFile(const DexFile& dex_file) { 2946 Thread* self = Thread::Current(); 2947 { 2948 ReaderMutexLock mu(self, dex_lock_); 2949 if (IsDexFileRegisteredLocked(dex_file)) { 2950 return; 2951 } 2952 } 2953 // Don't alloc while holding the lock, since allocation may need to 2954 // suspend all threads and another thread may need the dex_lock_ to 2955 // get to a suspend point. 2956 StackHandleScope<1> hs(self); 2957 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file))); 2958 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for " 2959 << dex_file.GetLocation(); 2960 { 2961 WriterMutexLock mu(self, dex_lock_); 2962 if (IsDexFileRegisteredLocked(dex_file)) { 2963 return; 2964 } 2965 RegisterDexFileLocked(dex_file, dex_cache); 2966 } 2967} 2968 2969void ClassLinker::RegisterDexFile(const DexFile& dex_file, 2970 Handle<mirror::DexCache> dex_cache) { 2971 WriterMutexLock mu(Thread::Current(), dex_lock_); 2972 RegisterDexFileLocked(dex_file, dex_cache); 2973} 2974 2975mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) { 2976 ReaderMutexLock mu(Thread::Current(), dex_lock_); 2977 // Search assuming unique-ness of dex file. 2978 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2979 mirror::DexCache* dex_cache = GetDexCache(i); 2980 if (dex_cache->GetDexFile() == &dex_file) { 2981 return dex_cache; 2982 } 2983 } 2984 // Search matching by location name. 2985 std::string location(dex_file.GetLocation()); 2986 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2987 mirror::DexCache* dex_cache = GetDexCache(i); 2988 if (dex_cache->GetDexFile()->GetLocation() == location) { 2989 return dex_cache; 2990 } 2991 } 2992 // Failure, dump diagnostic and abort. 2993 for (size_t i = 0; i != dex_caches_.size(); ++i) { 2994 mirror::DexCache* dex_cache = GetDexCache(i); 2995 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation(); 2996 } 2997 LOG(FATAL) << "Failed to find DexCache for DexFile " << location; 2998 return nullptr; 2999} 3000 3001void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) { 3002 ReaderMutexLock mu(Thread::Current(), dex_lock_); 3003 for (size_t i = 0; i != dex_caches_.size(); ++i) { 3004 mirror::DexCache* dex_cache = GetDexCache(i); 3005 dex_cache->Fixup(resolution_method); 3006 } 3007} 3008 3009mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) { 3010 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize()); 3011 if (UNLIKELY(klass == nullptr)) { 3012 return nullptr; 3013 } 3014 return InitializePrimitiveClass(klass, type); 3015} 3016 3017mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class, 3018 Primitive::Type type) { 3019 CHECK(primitive_class != nullptr); 3020 // Must hold lock on object when initializing. 3021 Thread* self = Thread::Current(); 3022 StackHandleScope<1> hs(self); 3023 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class)); 3024 ObjectLock<mirror::Class> lock(self, h_class); 3025 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract); 3026 primitive_class->SetPrimitiveType(type); 3027 primitive_class->SetStatus(mirror::Class::kStatusInitialized, self); 3028 const char* descriptor = Primitive::Descriptor(type); 3029 mirror::Class* existing = InsertClass(descriptor, primitive_class, 3030 ComputeModifiedUtf8Hash(descriptor)); 3031 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed"; 3032 return primitive_class; 3033} 3034 3035// Create an array class (i.e. the class object for the array, not the 3036// array itself). "descriptor" looks like "[C" or "[[[[B" or 3037// "[Ljava/lang/String;". 3038// 3039// If "descriptor" refers to an array of primitives, look up the 3040// primitive type's internally-generated class object. 3041// 3042// "class_loader" is the class loader of the class that's referring to 3043// us. It's used to ensure that we're looking for the element type in 3044// the right context. It does NOT become the class loader for the 3045// array class; that always comes from the base element class. 3046// 3047// Returns nullptr with an exception raised on failure. 3048mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash, 3049 Handle<mirror::ClassLoader> class_loader) { 3050 // Identify the underlying component type 3051 CHECK_EQ('[', descriptor[0]); 3052 StackHandleScope<2> hs(self); 3053 Handle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, class_loader))); 3054 if (component_type.Get() == nullptr) { 3055 DCHECK(self->IsExceptionPending()); 3056 // We need to accept erroneous classes as component types. 3057 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1); 3058 component_type.Assign(LookupClass(descriptor + 1, component_hash, class_loader.Get())); 3059 if (component_type.Get() == nullptr) { 3060 DCHECK(self->IsExceptionPending()); 3061 return nullptr; 3062 } else { 3063 self->ClearException(); 3064 } 3065 } 3066 if (UNLIKELY(component_type->IsPrimitiveVoid())) { 3067 ThrowNoClassDefFoundError("Attempt to create array of void primitive type"); 3068 return nullptr; 3069 } 3070 // See if the component type is already loaded. Array classes are 3071 // always associated with the class loader of their underlying 3072 // element type -- an array of Strings goes with the loader for 3073 // java/lang/String -- so we need to look for it there. (The 3074 // caller should have checked for the existence of the class 3075 // before calling here, but they did so with *their* class loader, 3076 // not the component type's loader.) 3077 // 3078 // If we find it, the caller adds "loader" to the class' initiating 3079 // loader list, which should prevent us from going through this again. 3080 // 3081 // This call is unnecessary if "loader" and "component_type->GetClassLoader()" 3082 // are the same, because our caller (FindClass) just did the 3083 // lookup. (Even if we get this wrong we still have correct behavior, 3084 // because we effectively do this lookup again when we add the new 3085 // class to the hash table --- necessary because of possible races with 3086 // other threads.) 3087 if (class_loader.Get() != component_type->GetClassLoader()) { 3088 mirror::Class* new_class = LookupClass(descriptor, hash, component_type->GetClassLoader()); 3089 if (new_class != nullptr) { 3090 return new_class; 3091 } 3092 } 3093 3094 // Fill out the fields in the Class. 3095 // 3096 // It is possible to execute some methods against arrays, because 3097 // all arrays are subclasses of java_lang_Object_, so we need to set 3098 // up a vtable. We can just point at the one in java_lang_Object_. 3099 // 3100 // Array classes are simple enough that we don't need to do a full 3101 // link step. 3102 auto new_class = hs.NewHandle<mirror::Class>(nullptr); 3103 if (UNLIKELY(!init_done_)) { 3104 // Classes that were hand created, ie not by FindSystemClass 3105 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) { 3106 new_class.Assign(GetClassRoot(kClassArrayClass)); 3107 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) { 3108 new_class.Assign(GetClassRoot(kObjectArrayClass)); 3109 } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) { 3110 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass)); 3111 } else if (strcmp(descriptor, 3112 class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) { 3113 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass)); 3114 } else if (strcmp(descriptor, 3115 class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) { 3116 new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass)); 3117 } else if (strcmp(descriptor, "[C") == 0) { 3118 new_class.Assign(GetClassRoot(kCharArrayClass)); 3119 } else if (strcmp(descriptor, "[I") == 0) { 3120 new_class.Assign(GetClassRoot(kIntArrayClass)); 3121 } 3122 } 3123 if (new_class.Get() == nullptr) { 3124 new_class.Assign(AllocClass(self, mirror::Array::ClassSize())); 3125 if (new_class.Get() == nullptr) { 3126 return nullptr; 3127 } 3128 new_class->SetComponentType(component_type.Get()); 3129 } 3130 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing. 3131 DCHECK(new_class->GetComponentType() != nullptr); 3132 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject); 3133 new_class->SetSuperClass(java_lang_Object); 3134 new_class->SetVTable(java_lang_Object->GetVTable()); 3135 new_class->SetPrimitiveType(Primitive::kPrimNot); 3136 new_class->SetClassLoader(component_type->GetClassLoader()); 3137 new_class->SetStatus(mirror::Class::kStatusLoaded, self); 3138 { 3139 StackHandleScope<mirror::Class::kImtSize> hs(self, 3140 Runtime::Current()->GetImtUnimplementedMethod()); 3141 new_class->PopulateEmbeddedImtAndVTable(&hs); 3142 } 3143 new_class->SetStatus(mirror::Class::kStatusInitialized, self); 3144 // don't need to set new_class->SetObjectSize(..) 3145 // because Object::SizeOf delegates to Array::SizeOf 3146 3147 3148 // All arrays have java/lang/Cloneable and java/io/Serializable as 3149 // interfaces. We need to set that up here, so that stuff like 3150 // "instanceof" works right. 3151 // 3152 // Note: The GC could run during the call to FindSystemClass, 3153 // so we need to make sure the class object is GC-valid while we're in 3154 // there. Do this by clearing the interface list so the GC will just 3155 // think that the entries are null. 3156 3157 3158 // Use the single, global copies of "interfaces" and "iftable" 3159 // (remember not to free them for arrays). 3160 { 3161 mirror::IfTable* array_iftable = array_iftable_.Read(); 3162 CHECK(array_iftable != nullptr); 3163 new_class->SetIfTable(array_iftable); 3164 } 3165 3166 // Inherit access flags from the component type. 3167 int access_flags = new_class->GetComponentType()->GetAccessFlags(); 3168 // Lose any implementation detail flags; in particular, arrays aren't finalizable. 3169 access_flags &= kAccJavaFlagsMask; 3170 // Arrays can't be used as a superclass or interface, so we want to add "abstract final" 3171 // and remove "interface". 3172 access_flags |= kAccAbstract | kAccFinal; 3173 access_flags &= ~kAccInterface; 3174 3175 new_class->SetAccessFlags(access_flags); 3176 3177 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash); 3178 if (existing == nullptr) { 3179 return new_class.Get(); 3180 } 3181 // Another thread must have loaded the class after we 3182 // started but before we finished. Abandon what we've 3183 // done. 3184 // 3185 // (Yes, this happens.) 3186 3187 return existing; 3188} 3189 3190mirror::Class* ClassLinker::FindPrimitiveClass(char type) { 3191 switch (type) { 3192 case 'B': 3193 return GetClassRoot(kPrimitiveByte); 3194 case 'C': 3195 return GetClassRoot(kPrimitiveChar); 3196 case 'D': 3197 return GetClassRoot(kPrimitiveDouble); 3198 case 'F': 3199 return GetClassRoot(kPrimitiveFloat); 3200 case 'I': 3201 return GetClassRoot(kPrimitiveInt); 3202 case 'J': 3203 return GetClassRoot(kPrimitiveLong); 3204 case 'S': 3205 return GetClassRoot(kPrimitiveShort); 3206 case 'Z': 3207 return GetClassRoot(kPrimitiveBoolean); 3208 case 'V': 3209 return GetClassRoot(kPrimitiveVoid); 3210 default: 3211 break; 3212 } 3213 std::string printable_type(PrintableChar(type)); 3214 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str()); 3215 return nullptr; 3216} 3217 3218mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, 3219 size_t hash) { 3220 if (VLOG_IS_ON(class_linker)) { 3221 mirror::DexCache* dex_cache = klass->GetDexCache(); 3222 std::string source; 3223 if (dex_cache != nullptr) { 3224 source += " from "; 3225 source += dex_cache->GetLocation()->ToModifiedUtf8(); 3226 } 3227 LOG(INFO) << "Loaded class " << descriptor << source; 3228 } 3229 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3230 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash); 3231 if (existing != nullptr) { 3232 return existing; 3233 } 3234 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr && 3235 dex_cache_image_class_lookup_required_) { 3236 // Check a class loaded with the system class loader matches one in the image if the class 3237 // is in the image. 3238 existing = LookupClassFromImage(descriptor); 3239 if (existing != nullptr) { 3240 CHECK_EQ(klass, existing); 3241 } 3242 } 3243 VerifyObject(klass); 3244 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash); 3245 if (log_new_class_table_roots_) { 3246 new_class_roots_.push_back(GcRoot<mirror::Class>(klass)); 3247 } 3248 return nullptr; 3249} 3250 3251mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass, 3252 size_t hash) { 3253 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3254 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()), 3255 hash); 3256 if (existing_it == class_table_.end()) { 3257 CHECK(klass->IsProxyClass()); 3258 return nullptr; 3259 } 3260 3261 mirror::Class* existing = existing_it->Read(); 3262 CHECK_NE(existing, klass) << descriptor; 3263 CHECK(!existing->IsResolved()) << descriptor; 3264 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor; 3265 3266 CHECK(!klass->IsTemp()) << descriptor; 3267 if (kIsDebugBuild && klass->GetClassLoader() == nullptr && 3268 dex_cache_image_class_lookup_required_) { 3269 // Check a class loaded with the system class loader matches one in the image if the class 3270 // is in the image. 3271 existing = LookupClassFromImage(descriptor); 3272 if (existing != nullptr) { 3273 CHECK_EQ(klass, existing) << descriptor; 3274 } 3275 } 3276 VerifyObject(klass); 3277 3278 // Update the element in the hash set. 3279 *existing_it = GcRoot<mirror::Class>(klass); 3280 if (log_new_class_table_roots_) { 3281 new_class_roots_.push_back(GcRoot<mirror::Class>(klass)); 3282 } 3283 3284 return existing; 3285} 3286 3287bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) { 3288 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3289 auto pair = std::make_pair(descriptor, class_loader); 3290 auto it = class_table_.Find(pair); 3291 if (it != class_table_.end()) { 3292 class_table_.Erase(it); 3293 return true; 3294 } 3295 it = pre_zygote_class_table_.Find(pair); 3296 if (it != pre_zygote_class_table_.end()) { 3297 pre_zygote_class_table_.Erase(it); 3298 return true; 3299 } 3300 return false; 3301} 3302 3303mirror::Class* ClassLinker::LookupClass(const char* descriptor, size_t hash, 3304 mirror::ClassLoader* class_loader) { 3305 { 3306 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3307 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash); 3308 if (result != nullptr) { 3309 return result; 3310 } 3311 } 3312 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) { 3313 return nullptr; 3314 } else { 3315 // Lookup failed but need to search dex_caches_. 3316 mirror::Class* result = LookupClassFromImage(descriptor); 3317 if (result != nullptr) { 3318 InsertClass(descriptor, result, hash); 3319 } else { 3320 // Searching the image dex files/caches failed, we don't want to get into this situation 3321 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image 3322 // classes into the class table. 3323 constexpr uint32_t kMaxFailedDexCacheLookups = 1000; 3324 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) { 3325 MoveImageClassesToClassTable(); 3326 } 3327 } 3328 return result; 3329 } 3330} 3331 3332mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor, 3333 mirror::ClassLoader* class_loader, 3334 size_t hash) { 3335 auto descriptor_pair = std::make_pair(descriptor, class_loader); 3336 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash); 3337 if (it == pre_zygote_class_table_.end()) { 3338 it = class_table_.FindWithHash(descriptor_pair, hash); 3339 if (it == class_table_.end()) { 3340 return nullptr; 3341 } 3342 } 3343 return it->Read(); 3344} 3345 3346static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches() 3347 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3348 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace(); 3349 CHECK(image != nullptr); 3350 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches); 3351 return root->AsObjectArray<mirror::DexCache>(); 3352} 3353 3354void ClassLinker::MoveImageClassesToClassTable() { 3355 Thread* self = Thread::Current(); 3356 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_); 3357 if (!dex_cache_image_class_lookup_required_) { 3358 return; // All dex cache classes are already in the class table. 3359 } 3360 const char* old_no_suspend_cause = 3361 self->StartAssertNoThreadSuspension("Moving image classes to class table"); 3362 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches(); 3363 std::string temp; 3364 for (int32_t i = 0; i < dex_caches->GetLength(); i++) { 3365 mirror::DexCache* dex_cache = dex_caches->Get(i); 3366 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes(); 3367 for (int32_t j = 0; j < types->GetLength(); j++) { 3368 mirror::Class* klass = types->Get(j); 3369 if (klass != nullptr) { 3370 DCHECK(klass->GetClassLoader() == nullptr); 3371 const char* descriptor = klass->GetDescriptor(&temp); 3372 size_t hash = ComputeModifiedUtf8Hash(descriptor); 3373 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash); 3374 if (existing != nullptr) { 3375 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != " 3376 << PrettyClassAndClassLoader(klass); 3377 } else { 3378 class_table_.Insert(GcRoot<mirror::Class>(klass)); 3379 if (log_new_class_table_roots_) { 3380 new_class_roots_.push_back(GcRoot<mirror::Class>(klass)); 3381 } 3382 } 3383 } 3384 } 3385 } 3386 dex_cache_image_class_lookup_required_ = false; 3387 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 3388} 3389 3390void ClassLinker::MoveClassTableToPreZygote() { 3391 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3392 DCHECK(pre_zygote_class_table_.Empty()); 3393 pre_zygote_class_table_ = std::move(class_table_); 3394 class_table_.Clear(); 3395} 3396 3397mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) { 3398 Thread* self = Thread::Current(); 3399 const char* old_no_suspend_cause = 3400 self->StartAssertNoThreadSuspension("Image class lookup"); 3401 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches(); 3402 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) { 3403 mirror::DexCache* dex_cache = dex_caches->Get(i); 3404 const DexFile* dex_file = dex_cache->GetDexFile(); 3405 // Try binary searching the string/type index. 3406 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor); 3407 if (string_id != nullptr) { 3408 const DexFile::TypeId* type_id = 3409 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id)); 3410 if (type_id != nullptr) { 3411 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id); 3412 mirror::Class* klass = dex_cache->GetResolvedType(type_idx); 3413 if (klass != nullptr) { 3414 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 3415 return klass; 3416 } 3417 } 3418 } 3419 } 3420 self->EndAssertNoThreadSuspension(old_no_suspend_cause); 3421 return nullptr; 3422} 3423 3424void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) { 3425 result.clear(); 3426 if (dex_cache_image_class_lookup_required_) { 3427 MoveImageClassesToClassTable(); 3428 } 3429 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 3430 while (true) { 3431 auto it = class_table_.Find(descriptor); 3432 if (it == class_table_.end()) { 3433 break; 3434 } 3435 result.push_back(it->Read()); 3436 class_table_.Erase(it); 3437 } 3438 for (mirror::Class* k : result) { 3439 class_table_.Insert(GcRoot<mirror::Class>(k)); 3440 } 3441 size_t pre_zygote_start = result.size(); 3442 // Now handle the pre zygote table. 3443 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only 3444 // called from the debugger. 3445 while (true) { 3446 auto it = pre_zygote_class_table_.Find(descriptor); 3447 if (it == pre_zygote_class_table_.end()) { 3448 break; 3449 } 3450 result.push_back(it->Read()); 3451 pre_zygote_class_table_.Erase(it); 3452 } 3453 for (size_t i = pre_zygote_start; i < result.size(); ++i) { 3454 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i])); 3455 } 3456} 3457 3458void ClassLinker::VerifyClass(Handle<mirror::Class> klass) { 3459 // TODO: assert that the monitor on the Class is held 3460 Thread* self = Thread::Current(); 3461 ObjectLock<mirror::Class> lock(self, klass); 3462 3463 // Don't attempt to re-verify if already sufficiently verified. 3464 if (klass->IsVerified()) { 3465 EnsurePreverifiedMethods(klass); 3466 return; 3467 } 3468 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) { 3469 return; 3470 } 3471 3472 // The class might already be erroneous, for example at compile time if we attempted to verify 3473 // this class as a parent to another. 3474 if (klass->IsErroneous()) { 3475 ThrowEarlierClassFailure(klass.Get()); 3476 return; 3477 } 3478 3479 if (klass->GetStatus() == mirror::Class::kStatusResolved) { 3480 klass->SetStatus(mirror::Class::kStatusVerifying, self); 3481 } else { 3482 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime) 3483 << PrettyClass(klass.Get()); 3484 CHECK(!Runtime::Current()->IsCompiler()); 3485 klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self); 3486 } 3487 3488 // Skip verification if disabled. 3489 if (!Runtime::Current()->IsVerificationEnabled()) { 3490 klass->SetStatus(mirror::Class::kStatusVerified, self); 3491 EnsurePreverifiedMethods(klass); 3492 return; 3493 } 3494 3495 // Verify super class. 3496 StackHandleScope<2> hs(self); 3497 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass())); 3498 if (super.Get() != nullptr) { 3499 // Acquire lock to prevent races on verifying the super class. 3500 ObjectLock<mirror::Class> lock(self, super); 3501 3502 if (!super->IsVerified() && !super->IsErroneous()) { 3503 VerifyClass(super); 3504 } 3505 if (!super->IsCompileTimeVerified()) { 3506 std::string error_msg( 3507 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s", 3508 PrettyDescriptor(klass.Get()).c_str(), 3509 PrettyDescriptor(super.Get()).c_str())); 3510 LOG(ERROR) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 3511 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr))); 3512 if (cause.Get() != nullptr) { 3513 self->ClearException(); 3514 } 3515 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str()); 3516 if (cause.Get() != nullptr) { 3517 self->GetException(nullptr)->SetCause(cause.Get()); 3518 } 3519 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex()); 3520 if (Runtime::Current()->IsCompiler()) { 3521 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref); 3522 } 3523 klass->SetStatus(mirror::Class::kStatusError, self); 3524 return; 3525 } 3526 } 3527 3528 // Try to use verification information from the oat file, otherwise do runtime verification. 3529 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile(); 3530 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady); 3531 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status); 3532 if (oat_file_class_status == mirror::Class::kStatusError) { 3533 VLOG(class_linker) << "Skipping runtime verification of erroneous class " 3534 << PrettyDescriptor(klass.Get()) << " in " 3535 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8(); 3536 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification", 3537 PrettyDescriptor(klass.Get()).c_str()); 3538 klass->SetStatus(mirror::Class::kStatusError, self); 3539 return; 3540 } 3541 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure; 3542 std::string error_msg; 3543 if (!preverified) { 3544 verifier_failure = verifier::MethodVerifier::VerifyClass(klass.Get(), 3545 Runtime::Current()->IsCompiler(), 3546 &error_msg); 3547 } 3548 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) { 3549 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) { 3550 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get()) 3551 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 3552 << " because: " << error_msg; 3553 } 3554 self->AssertNoPendingException(); 3555 // Make sure all classes referenced by catch blocks are resolved. 3556 ResolveClassExceptionHandlerTypes(dex_file, klass); 3557 if (verifier_failure == verifier::MethodVerifier::kNoFailure) { 3558 // Even though there were no verifier failures we need to respect whether the super-class 3559 // was verified or requiring runtime reverification. 3560 if (super.Get() == nullptr || super->IsVerified()) { 3561 klass->SetStatus(mirror::Class::kStatusVerified, self); 3562 } else { 3563 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 3564 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self); 3565 // Pretend a soft failure occured so that we don't consider the class verified below. 3566 verifier_failure = verifier::MethodVerifier::kSoftFailure; 3567 } 3568 } else { 3569 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure); 3570 // Soft failures at compile time should be retried at runtime. Soft 3571 // failures at runtime will be handled by slow paths in the generated 3572 // code. Set status accordingly. 3573 if (Runtime::Current()->IsCompiler()) { 3574 klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self); 3575 } else { 3576 klass->SetStatus(mirror::Class::kStatusVerified, self); 3577 // As this is a fake verified status, make sure the methods are _not_ marked preverified 3578 // later. 3579 klass->SetAccessFlags(klass->GetAccessFlags() | kAccPreverified); 3580 } 3581 } 3582 } else { 3583 LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get()) 3584 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8() 3585 << " because: " << error_msg; 3586 self->AssertNoPendingException(); 3587 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str()); 3588 klass->SetStatus(mirror::Class::kStatusError, self); 3589 } 3590 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) { 3591 // Class is verified so we don't need to do any access check on its methods. 3592 // Let the interpreter know it by setting the kAccPreverified flag onto each 3593 // method. 3594 // Note: we're going here during compilation and at runtime. When we set the 3595 // kAccPreverified flag when compiling image classes, the flag is recorded 3596 // in the image and is set when loading the image. 3597 EnsurePreverifiedMethods(klass); 3598 } 3599} 3600 3601void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) { 3602 if ((klass->GetAccessFlags() & kAccPreverified) == 0) { 3603 klass->SetPreverifiedFlagOnAllMethods(); 3604 klass->SetAccessFlags(klass->GetAccessFlags() | kAccPreverified); 3605 } 3606} 3607 3608bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass, 3609 mirror::Class::Status& oat_file_class_status) { 3610 // If we're compiling, we can only verify the class using the oat file if 3611 // we are not compiling the image or if the class we're verifying is not part of 3612 // the app. In other words, we will only check for preverification of bootclasspath 3613 // classes. 3614 if (Runtime::Current()->IsCompiler()) { 3615 // Are we compiling the bootclasspath? 3616 if (!Runtime::Current()->UseCompileTimeClassPath()) { 3617 return false; 3618 } 3619 // We are compiling an app (not the image). 3620 3621 // Is this an app class? (I.e. not a bootclasspath class) 3622 if (klass->GetClassLoader() != nullptr) { 3623 return false; 3624 } 3625 } 3626 3627 const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file); 3628 // In case we run without an image there won't be a backing oat file. 3629 if (oat_dex_file == nullptr) { 3630 return false; 3631 } 3632 3633 uint16_t class_def_index = klass->GetDexClassDefIndex(); 3634 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus(); 3635 if (oat_file_class_status == mirror::Class::kStatusVerified || 3636 oat_file_class_status == mirror::Class::kStatusInitialized) { 3637 return true; 3638 } 3639 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) { 3640 // Compile time verification failed with a soft error. Compile time verification can fail 3641 // because we have incomplete type information. Consider the following: 3642 // class ... { 3643 // Foo x; 3644 // .... () { 3645 // if (...) { 3646 // v1 gets assigned a type of resolved class Foo 3647 // } else { 3648 // v1 gets assigned a type of unresolved class Bar 3649 // } 3650 // iput x = v1 3651 // } } 3652 // when we merge v1 following the if-the-else it results in Conflict 3653 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be 3654 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as 3655 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk 3656 // at compile time). 3657 return false; 3658 } 3659 if (oat_file_class_status == mirror::Class::kStatusError) { 3660 // Compile time verification failed with a hard error. This is caused by invalid instructions 3661 // in the class. These errors are unrecoverable. 3662 return false; 3663 } 3664 if (oat_file_class_status == mirror::Class::kStatusNotReady) { 3665 // Status is uninitialized if we couldn't determine the status at compile time, for example, 3666 // not loading the class. 3667 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy 3668 // isn't a problem and this case shouldn't occur 3669 return false; 3670 } 3671 std::string temp; 3672 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status 3673 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " " 3674 << klass->GetDescriptor(&temp); 3675 3676 return false; 3677} 3678 3679void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, 3680 Handle<mirror::Class> klass) { 3681 for (size_t i = 0; i < klass->NumDirectMethods(); i++) { 3682 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i)); 3683 } 3684 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) { 3685 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i)); 3686 } 3687} 3688 3689void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, 3690 mirror::ArtMethod* method) { 3691 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod. 3692 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset()); 3693 if (code_item == nullptr) { 3694 return; // native or abstract method 3695 } 3696 if (code_item->tries_size_ == 0) { 3697 return; // nothing to process 3698 } 3699 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0); 3700 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr); 3701 ClassLinker* linker = Runtime::Current()->GetClassLinker(); 3702 for (uint32_t idx = 0; idx < handlers_size; idx++) { 3703 CatchHandlerIterator iterator(handlers_ptr); 3704 for (; iterator.HasNext(); iterator.Next()) { 3705 // Ensure exception types are resolved so that they don't need resolution to be delivered, 3706 // unresolved exception types will be ignored by exception delivery 3707 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) { 3708 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method); 3709 if (exception_type == nullptr) { 3710 DCHECK(Thread::Current()->IsExceptionPending()); 3711 Thread::Current()->ClearException(); 3712 } 3713 } 3714 } 3715 handlers_ptr = iterator.EndDataPointer(); 3716 } 3717} 3718 3719static void CheckProxyConstructor(mirror::ArtMethod* constructor); 3720static void CheckProxyMethod(Handle<mirror::ArtMethod> method, 3721 Handle<mirror::ArtMethod> prototype); 3722 3723mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name, 3724 jobjectArray interfaces, jobject loader, 3725 jobjectArray methods, jobjectArray throws) { 3726 Thread* self = soa.Self(); 3727 StackHandleScope<8> hs(self); 3728 Handle<mirror::Class> klass(hs.NewHandle( 3729 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class)))); 3730 if (klass.Get() == nullptr) { 3731 CHECK(self->IsExceptionPending()); // OOME. 3732 return nullptr; 3733 } 3734 DCHECK(klass->GetClass() != nullptr); 3735 klass->SetObjectSize(sizeof(mirror::Proxy)); 3736 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods. 3737 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified); 3738 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader)); 3739 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot); 3740 klass->SetName(soa.Decode<mirror::String*>(name)); 3741 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy); 3742 klass->SetDexCache(proxy_class->GetDexCache()); 3743 klass->SetStatus(mirror::Class::kStatusIdx, self); 3744 3745 // Instance fields are inherited, but we add a couple of static fields... 3746 { 3747 mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2); 3748 if (UNLIKELY(sfields == nullptr)) { 3749 CHECK(self->IsExceptionPending()); // OOME. 3750 return nullptr; 3751 } 3752 klass->SetSFields(sfields); 3753 } 3754 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by 3755 // our proxy, so Class.getInterfaces doesn't return the flattened set. 3756 Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self))); 3757 if (UNLIKELY(interfaces_sfield.Get() == nullptr)) { 3758 CHECK(self->IsExceptionPending()); // OOME. 3759 return nullptr; 3760 } 3761 klass->SetStaticField(0, interfaces_sfield.Get()); 3762 interfaces_sfield->SetDexFieldIndex(0); 3763 interfaces_sfield->SetDeclaringClass(klass.Get()); 3764 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 3765 // 2. Create a static field 'throws' that holds exceptions thrown by our methods. 3766 Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self))); 3767 if (UNLIKELY(throws_sfield.Get() == nullptr)) { 3768 CHECK(self->IsExceptionPending()); // OOME. 3769 return nullptr; 3770 } 3771 klass->SetStaticField(1, throws_sfield.Get()); 3772 throws_sfield->SetDexFieldIndex(1); 3773 throws_sfield->SetDeclaringClass(klass.Get()); 3774 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal); 3775 3776 // Proxies have 1 direct method, the constructor 3777 { 3778 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1); 3779 if (UNLIKELY(directs == nullptr)) { 3780 CHECK(self->IsExceptionPending()); // OOME. 3781 return nullptr; 3782 } 3783 klass->SetDirectMethods(directs); 3784 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class); 3785 if (UNLIKELY(constructor == nullptr)) { 3786 CHECK(self->IsExceptionPending()); // OOME. 3787 return nullptr; 3788 } 3789 klass->SetDirectMethod(0, constructor); 3790 } 3791 3792 // Create virtual method using specified prototypes. 3793 size_t num_virtual_methods = 3794 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength(); 3795 { 3796 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self, 3797 num_virtual_methods); 3798 if (UNLIKELY(virtuals == nullptr)) { 3799 CHECK(self->IsExceptionPending()); // OOME. 3800 return nullptr; 3801 } 3802 klass->SetVirtualMethods(virtuals); 3803 } 3804 for (size_t i = 0; i < num_virtual_methods; ++i) { 3805 StackHandleScope<1> hs(self); 3806 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods = 3807 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods); 3808 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i))); 3809 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype); 3810 if (UNLIKELY(clone == nullptr)) { 3811 CHECK(self->IsExceptionPending()); // OOME. 3812 return nullptr; 3813 } 3814 klass->SetVirtualMethod(i, clone); 3815 } 3816 3817 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy 3818 klass->SetStatus(mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state. 3819 self->AssertNoPendingException(); 3820 3821 std::string descriptor(GetDescriptorForProxy(klass.Get())); 3822 mirror::Class* new_class = nullptr; 3823 { 3824 // Must hold lock on object when resolved. 3825 ObjectLock<mirror::Class> resolution_lock(self, klass); 3826 // Link the fields and virtual methods, creating vtable and iftables 3827 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces( 3828 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces))); 3829 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) { 3830 klass->SetStatus(mirror::Class::kStatusError, self); 3831 return nullptr; 3832 } 3833 } 3834 3835 CHECK(klass->IsRetired()); 3836 CHECK_NE(klass.Get(), new_class); 3837 klass.Assign(new_class); 3838 3839 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class); 3840 interfaces_sfield->SetObject<false>(klass.Get(), 3841 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)); 3842 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class); 3843 throws_sfield->SetObject<false>(klass.Get(), 3844 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws)); 3845 3846 { 3847 // Lock on klass is released. Lock new class object. 3848 ObjectLock<mirror::Class> initialization_lock(self, klass); 3849 klass->SetStatus(mirror::Class::kStatusInitialized, self); 3850 } 3851 3852 // sanity checks 3853 if (kIsDebugBuild) { 3854 CHECK(klass->GetIFields() == nullptr); 3855 CheckProxyConstructor(klass->GetDirectMethod(0)); 3856 for (size_t i = 0; i < num_virtual_methods; ++i) { 3857 StackHandleScope<2> hs(self); 3858 mirror::ObjectArray<mirror::ArtMethod>* decoded_methods = 3859 soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods); 3860 Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i))); 3861 Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i))); 3862 CheckProxyMethod(virtual_method, prototype); 3863 } 3864 3865 mirror::String* decoded_name = soa.Decode<mirror::String*>(name); 3866 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces", 3867 decoded_name->ToModifiedUtf8().c_str())); 3868 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name); 3869 3870 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws", 3871 decoded_name->ToModifiedUtf8().c_str())); 3872 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name); 3873 3874 CHECK_EQ(klass.Get()->GetInterfaces(), 3875 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)); 3876 CHECK_EQ(klass.Get()->GetThrows(), 3877 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws)); 3878 } 3879 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), 3880 ComputeModifiedUtf8Hash(descriptor.c_str())); 3881 CHECK(existing == nullptr); 3882 return klass.Get(); 3883} 3884 3885std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) { 3886 DCHECK(proxy_class->IsProxyClass()); 3887 mirror::String* name = proxy_class->GetName(); 3888 DCHECK(name != nullptr); 3889 return DotToDescriptor(name->ToModifiedUtf8().c_str()); 3890} 3891 3892mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class, 3893 mirror::ArtMethod* proxy_method) { 3894 DCHECK(proxy_class->IsProxyClass()); 3895 DCHECK(proxy_method->IsProxyMethod()); 3896 // Locate the dex cache of the original interface/Object 3897 mirror::DexCache* dex_cache = nullptr; 3898 { 3899 ReaderMutexLock mu(Thread::Current(), dex_lock_); 3900 for (size_t i = 0; i != dex_caches_.size(); ++i) { 3901 mirror::DexCache* a_dex_cache = GetDexCache(i); 3902 if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) { 3903 dex_cache = a_dex_cache; 3904 break; 3905 } 3906 } 3907 } 3908 CHECK(dex_cache != nullptr); 3909 uint32_t method_idx = proxy_method->GetDexMethodIndex(); 3910 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx); 3911 CHECK(resolved_method != nullptr); 3912 return resolved_method; 3913} 3914 3915 3916mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self, 3917 Handle<mirror::Class> klass, 3918 mirror::Class* proxy_class) { 3919 // Create constructor for Proxy that must initialize h 3920 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods = 3921 proxy_class->GetDirectMethods(); 3922 CHECK_EQ(proxy_direct_methods->GetLength(), 16); 3923 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2); 3924 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden 3925 // constructor method. 3926 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(), 3927 proxy_constructor); 3928 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its 3929 // code_ too) 3930 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self)); 3931 if (constructor == nullptr) { 3932 CHECK(self->IsExceptionPending()); // OOME. 3933 return nullptr; 3934 } 3935 // Make this constructor public and fix the class to be our Proxy version 3936 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic); 3937 constructor->SetDeclaringClass(klass.Get()); 3938 return constructor; 3939} 3940 3941static void CheckProxyConstructor(mirror::ArtMethod* constructor) 3942 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3943 CHECK(constructor->IsConstructor()); 3944 CHECK_STREQ(constructor->GetName(), "<init>"); 3945 CHECK_STREQ(constructor->GetSignature().ToString().c_str(), 3946 "(Ljava/lang/reflect/InvocationHandler;)V"); 3947 DCHECK(constructor->IsPublic()); 3948} 3949 3950mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self, 3951 Handle<mirror::Class> klass, 3952 Handle<mirror::ArtMethod> prototype) { 3953 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden 3954 // prototype method 3955 prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(), 3956 prototype.Get()); 3957 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize 3958 // as necessary 3959 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self)); 3960 if (UNLIKELY(method == nullptr)) { 3961 CHECK(self->IsExceptionPending()); // OOME. 3962 return nullptr; 3963 } 3964 3965 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to 3966 // the intersection of throw exceptions as defined in Proxy 3967 method->SetDeclaringClass(klass.Get()); 3968 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal); 3969 3970 // At runtime the method looks like a reference and argument saving method, clone the code 3971 // related parameters from this method. 3972 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler()); 3973#if defined(ART_USE_PORTABLE_COMPILER) 3974 method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler()); 3975#endif 3976 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge); 3977 3978 return method; 3979} 3980 3981static void CheckProxyMethod(Handle<mirror::ArtMethod> method, Handle<mirror::ArtMethod> prototype) 3982 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 3983 // Basic sanity 3984 CHECK(!prototype->IsFinal()); 3985 CHECK(method->IsFinal()); 3986 CHECK(!method->IsAbstract()); 3987 3988 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its 3989 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself. 3990 CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings()); 3991 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get())); 3992 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get())); 3993 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex()); 3994 3995 MethodHelper mh(method); 3996 MethodHelper mh2(prototype); 3997 CHECK_STREQ(method->GetName(), prototype->GetName()); 3998 CHECK_STREQ(method->GetShorty(), prototype->GetShorty()); 3999 // More complex sanity - via dex cache 4000 CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType()); 4001} 4002 4003static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics, 4004 bool can_init_parents) 4005 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4006 if (can_init_statics && can_init_parents) { 4007 return true; 4008 } 4009 if (!can_init_statics) { 4010 // Check if there's a class initializer. 4011 mirror::ArtMethod* clinit = klass->FindClassInitializer(); 4012 if (clinit != nullptr) { 4013 return false; 4014 } 4015 // Check if there are encoded static values needing initialization. 4016 if (klass->NumStaticFields() != 0) { 4017 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 4018 DCHECK(dex_class_def != nullptr); 4019 if (dex_class_def->static_values_off_ != 0) { 4020 return false; 4021 } 4022 } 4023 } 4024 if (!klass->IsInterface() && klass->HasSuperClass()) { 4025 mirror::Class* super_class = klass->GetSuperClass(); 4026 if (!can_init_parents && !super_class->IsInitialized()) { 4027 return false; 4028 } else { 4029 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) { 4030 return false; 4031 } 4032 } 4033 } 4034 return true; 4035} 4036 4037bool ClassLinker::IsInitialized() const { 4038 return init_done_; 4039} 4040 4041bool ClassLinker::InitializeClass(Handle<mirror::Class> klass, bool can_init_statics, 4042 bool can_init_parents) { 4043 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol 4044 4045 // Are we already initialized and therefore done? 4046 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as 4047 // an initialized class will never change its state. 4048 if (klass->IsInitialized()) { 4049 return true; 4050 } 4051 4052 // Fast fail if initialization requires a full runtime. Not part of the JLS. 4053 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) { 4054 return false; 4055 } 4056 4057 Thread* self = Thread::Current(); 4058 uint64_t t0; 4059 { 4060 ObjectLock<mirror::Class> lock(self, klass); 4061 4062 // Re-check under the lock in case another thread initialized ahead of us. 4063 if (klass->IsInitialized()) { 4064 return true; 4065 } 4066 4067 // Was the class already found to be erroneous? Done under the lock to match the JLS. 4068 if (klass->IsErroneous()) { 4069 ThrowEarlierClassFailure(klass.Get()); 4070 return false; 4071 } 4072 4073 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus(); 4074 4075 if (!klass->IsVerified()) { 4076 VerifyClass(klass); 4077 if (!klass->IsVerified()) { 4078 // We failed to verify, expect either the klass to be erroneous or verification failed at 4079 // compile time. 4080 if (klass->IsErroneous()) { 4081 CHECK(self->IsExceptionPending()); 4082 } else { 4083 CHECK(Runtime::Current()->IsCompiler()); 4084 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime); 4085 } 4086 return false; 4087 } else { 4088 self->AssertNoPendingException(); 4089 } 4090 } 4091 4092 // If the class is kStatusInitializing, either this thread is 4093 // initializing higher up the stack or another thread has beat us 4094 // to initializing and we need to wait. Either way, this 4095 // invocation of InitializeClass will not be responsible for 4096 // running <clinit> and will return. 4097 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 4098 // Could have got an exception during verification. 4099 if (self->IsExceptionPending()) { 4100 return false; 4101 } 4102 // We caught somebody else in the act; was it us? 4103 if (klass->GetClinitThreadId() == self->GetTid()) { 4104 // Yes. That's fine. Return so we can continue initializing. 4105 return true; 4106 } 4107 // No. That's fine. Wait for another thread to finish initializing. 4108 return WaitForInitializeClass(klass, self, lock); 4109 } 4110 4111 if (!ValidateSuperClassDescriptors(klass)) { 4112 klass->SetStatus(mirror::Class::kStatusError, self); 4113 return false; 4114 } 4115 4116 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get()); 4117 4118 // From here out other threads may observe that we're initializing and so changes of state 4119 // require the a notification. 4120 klass->SetClinitThreadId(self->GetTid()); 4121 klass->SetStatus(mirror::Class::kStatusInitializing, self); 4122 4123 t0 = NanoTime(); 4124 } 4125 4126 // Initialize super classes, must be done while initializing for the JLS. 4127 if (!klass->IsInterface() && klass->HasSuperClass()) { 4128 mirror::Class* super_class = klass->GetSuperClass(); 4129 if (!super_class->IsInitialized()) { 4130 CHECK(!super_class->IsInterface()); 4131 CHECK(can_init_parents); 4132 StackHandleScope<1> hs(self); 4133 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class)); 4134 bool super_initialized = InitializeClass(handle_scope_super, can_init_statics, true); 4135 if (!super_initialized) { 4136 // The super class was verified ahead of entering initializing, we should only be here if 4137 // the super class became erroneous due to initialization. 4138 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending()) 4139 << "Super class initialization failed for " 4140 << PrettyDescriptor(handle_scope_super.Get()) 4141 << " that has unexpected status " << handle_scope_super->GetStatus() 4142 << "\nPending exception:\n" 4143 << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : ""); 4144 ObjectLock<mirror::Class> lock(self, klass); 4145 // Initialization failed because the super-class is erroneous. 4146 klass->SetStatus(mirror::Class::kStatusError, self); 4147 return false; 4148 } 4149 } 4150 } 4151 4152 const size_t num_static_fields = klass->NumStaticFields(); 4153 if (num_static_fields > 0) { 4154 const DexFile::ClassDef* dex_class_def = klass->GetClassDef(); 4155 CHECK(dex_class_def != nullptr); 4156 const DexFile& dex_file = klass->GetDexFile(); 4157 StackHandleScope<2> hs(self); 4158 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader())); 4159 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache())); 4160 4161 // Eagerly fill in static fields so that the we don't have to do as many expensive 4162 // Class::FindStaticField in ResolveField. 4163 for (size_t i = 0; i < num_static_fields; ++i) { 4164 mirror::ArtField* field = klass->GetStaticField(i); 4165 const uint32_t field_idx = field->GetDexFieldIndex(); 4166 mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx); 4167 if (resolved_field == nullptr) { 4168 dex_cache->SetResolvedField(field_idx, field); 4169 } else { 4170 DCHECK_EQ(field, resolved_field); 4171 } 4172 } 4173 4174 EncodedStaticFieldValueIterator it(dex_file, &dex_cache, &class_loader, 4175 this, *dex_class_def); 4176 if (it.HasNext()) { 4177 CHECK(can_init_statics); 4178 // We reordered the fields, so we need to be able to map the 4179 // field indexes to the right fields. 4180 SafeMap<uint32_t, mirror::ArtField*> field_map; 4181 ConstructFieldMap(dex_file, *dex_class_def, klass.Get(), field_map); 4182 for (size_t i = 0; it.HasNext(); i++, it.Next()) { 4183 if (Runtime::Current()->IsActiveTransaction()) { 4184 it.ReadValueToField<true>(field_map.Get(i)); 4185 } else { 4186 it.ReadValueToField<false>(field_map.Get(i)); 4187 } 4188 } 4189 } 4190 } 4191 4192 mirror::ArtMethod* clinit = klass->FindClassInitializer(); 4193 if (clinit != nullptr) { 4194 CHECK(can_init_statics); 4195 JValue result; 4196 clinit->Invoke(self, nullptr, 0, &result, "V"); 4197 } 4198 4199 uint64_t t1 = NanoTime(); 4200 4201 bool success = true; 4202 { 4203 ObjectLock<mirror::Class> lock(self, klass); 4204 4205 if (self->IsExceptionPending()) { 4206 WrapExceptionInInitializer(); 4207 klass->SetStatus(mirror::Class::kStatusError, self); 4208 success = false; 4209 } else { 4210 RuntimeStats* global_stats = Runtime::Current()->GetStats(); 4211 RuntimeStats* thread_stats = self->GetStats(); 4212 ++global_stats->class_init_count; 4213 ++thread_stats->class_init_count; 4214 global_stats->class_init_time_ns += (t1 - t0); 4215 thread_stats->class_init_time_ns += (t1 - t0); 4216 // Set the class as initialized except if failed to initialize static fields. 4217 klass->SetStatus(mirror::Class::kStatusInitialized, self); 4218 if (VLOG_IS_ON(class_linker)) { 4219 std::string temp; 4220 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " << 4221 klass->GetLocation(); 4222 } 4223 // Opportunistically set static method trampolines to their destination. 4224 FixupStaticTrampolines(klass.Get()); 4225 } 4226 } 4227 return success; 4228} 4229 4230bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self, 4231 ObjectLock<mirror::Class>& lock) 4232 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4233 while (true) { 4234 self->AssertNoPendingException(); 4235 CHECK(!klass->IsInitialized()); 4236 lock.WaitIgnoringInterrupts(); 4237 4238 // When we wake up, repeat the test for init-in-progress. If 4239 // there's an exception pending (only possible if 4240 // "interruptShouldThrow" was set), bail out. 4241 if (self->IsExceptionPending()) { 4242 WrapExceptionInInitializer(); 4243 klass->SetStatus(mirror::Class::kStatusError, self); 4244 return false; 4245 } 4246 // Spurious wakeup? Go back to waiting. 4247 if (klass->GetStatus() == mirror::Class::kStatusInitializing) { 4248 continue; 4249 } 4250 if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) { 4251 // Compile time initialization failed. 4252 return false; 4253 } 4254 if (klass->IsErroneous()) { 4255 // The caller wants an exception, but it was thrown in a 4256 // different thread. Synthesize one here. 4257 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread", 4258 PrettyDescriptor(klass.Get()).c_str()); 4259 return false; 4260 } 4261 if (klass->IsInitialized()) { 4262 return true; 4263 } 4264 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is " 4265 << klass->GetStatus(); 4266 } 4267 LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get()); 4268} 4269 4270bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) { 4271 if (klass->IsInterface()) { 4272 return true; 4273 } 4274 // Begin with the methods local to the superclass. 4275 StackHandleScope<2> hs(Thread::Current()); 4276 MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4277 MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr)); 4278 if (klass->HasSuperClass() && 4279 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) { 4280 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) { 4281 mh.ChangeMethod(klass->GetVTableEntry(i)); 4282 super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i)); 4283 if (mh.GetMethod() != super_mh.GetMethod() && 4284 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) { 4285 ThrowLinkageError(klass.Get(), 4286 "Class %s method %s resolves differently in superclass %s", 4287 PrettyDescriptor(klass.Get()).c_str(), 4288 PrettyMethod(mh.GetMethod()).c_str(), 4289 PrettyDescriptor(klass->GetSuperClass()).c_str()); 4290 return false; 4291 } 4292 } 4293 } 4294 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) { 4295 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) { 4296 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods(); 4297 for (uint32_t j = 0; j < num_methods; ++j) { 4298 mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j)); 4299 super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j)); 4300 if (mh.GetMethod() != super_mh.GetMethod() && 4301 !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) { 4302 ThrowLinkageError(klass.Get(), 4303 "Class %s method %s resolves differently in interface %s", 4304 PrettyDescriptor(klass.Get()).c_str(), 4305 PrettyMethod(mh.GetMethod()).c_str(), 4306 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str()); 4307 return false; 4308 } 4309 } 4310 } 4311 } 4312 return true; 4313} 4314 4315bool ClassLinker::EnsureInitialized(Handle<mirror::Class> c, bool can_init_fields, 4316 bool can_init_parents) { 4317 DCHECK(c.Get() != nullptr); 4318 if (c->IsInitialized()) { 4319 EnsurePreverifiedMethods(c); 4320 return true; 4321 } 4322 const bool success = InitializeClass(c, can_init_fields, can_init_parents); 4323 Thread* self = Thread::Current(); 4324 if (!success) { 4325 if (can_init_fields && can_init_parents) { 4326 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get()); 4327 } 4328 } else { 4329 self->AssertNoPendingException(); 4330 } 4331 return success; 4332} 4333 4334void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def, 4335 mirror::Class* c, 4336 SafeMap<uint32_t, mirror::ArtField*>& field_map) { 4337 const byte* class_data = dex_file.GetClassData(dex_class_def); 4338 ClassDataItemIterator it(dex_file, class_data); 4339 StackHandleScope<2> hs(Thread::Current()); 4340 Handle<mirror::DexCache> dex_cache(hs.NewHandle(c->GetDexCache())); 4341 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(c->GetClassLoader())); 4342 CHECK(!kMovingFields); 4343 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) { 4344 field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), dex_cache, class_loader, true)); 4345 } 4346} 4347 4348void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) { 4349 mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields(); 4350 if (fields != nullptr) { 4351 for (int index = 0; index < fields->GetLength(); index ++) { 4352 if (fields->Get(index)->GetDeclaringClass() == temp_class) { 4353 fields->Get(index)->SetDeclaringClass(new_class); 4354 } 4355 } 4356 } 4357 4358 fields = new_class->GetSFields(); 4359 if (fields != nullptr) { 4360 for (int index = 0; index < fields->GetLength(); index ++) { 4361 if (fields->Get(index)->GetDeclaringClass() == temp_class) { 4362 fields->Get(index)->SetDeclaringClass(new_class); 4363 } 4364 } 4365 } 4366 4367 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods(); 4368 if (methods != nullptr) { 4369 for (int index = 0; index < methods->GetLength(); index ++) { 4370 if (methods->Get(index)->GetDeclaringClass() == temp_class) { 4371 methods->Get(index)->SetDeclaringClass(new_class); 4372 } 4373 } 4374 } 4375 4376 methods = new_class->GetVirtualMethods(); 4377 if (methods != nullptr) { 4378 for (int index = 0; index < methods->GetLength(); index ++) { 4379 if (methods->Get(index)->GetDeclaringClass() == temp_class) { 4380 methods->Get(index)->SetDeclaringClass(new_class); 4381 } 4382 } 4383 } 4384} 4385 4386bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass, 4387 Handle<mirror::ObjectArray<mirror::Class>> interfaces, 4388 mirror::Class** new_class) { 4389 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 4390 4391 if (!LinkSuperClass(klass)) { 4392 return false; 4393 } 4394 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope( 4395 self, Runtime::Current()->GetImtUnimplementedMethod()); 4396 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) { 4397 return false; 4398 } 4399 if (!LinkInstanceFields(klass)) { 4400 return false; 4401 } 4402 size_t class_size; 4403 if (!LinkStaticFields(klass, &class_size)) { 4404 return false; 4405 } 4406 CreateReferenceInstanceOffsets(klass); 4407 CreateReferenceStaticOffsets(klass); 4408 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus()); 4409 4410 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) { 4411 // We don't need to retire this class as it has no embedded tables or it was created the 4412 // correct size during class linker initialization. 4413 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get()); 4414 4415 if (klass->ShouldHaveEmbeddedImtAndVTable()) { 4416 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope); 4417 } 4418 4419 // This will notify waiters on klass that saw the not yet resolved 4420 // class in the class_table_ during EnsureResolved. 4421 klass->SetStatus(mirror::Class::kStatusResolved, self); 4422 *new_class = klass.Get(); 4423 } else { 4424 CHECK(!klass->IsResolved()); 4425 // Retire the temporary class and create the correctly sized resolved class. 4426 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope); 4427 if (UNLIKELY(*new_class == nullptr)) { 4428 CHECK(self->IsExceptionPending()); // Expect an OOME. 4429 klass->SetStatus(mirror::Class::kStatusError, self); 4430 return false; 4431 } 4432 4433 CHECK_EQ((*new_class)->GetClassSize(), class_size); 4434 StackHandleScope<1> hs(self); 4435 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class); 4436 ObjectLock<mirror::Class> lock(self, new_class_h); 4437 4438 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get()); 4439 4440 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), 4441 ComputeModifiedUtf8Hash(descriptor)); 4442 CHECK(existing == nullptr || existing == klass.Get()); 4443 4444 // This will notify waiters on temp class that saw the not yet resolved class in the 4445 // class_table_ during EnsureResolved. 4446 klass->SetStatus(mirror::Class::kStatusRetired, self); 4447 4448 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving); 4449 // This will notify waiters on new_class that saw the not yet resolved 4450 // class in the class_table_ during EnsureResolved. 4451 new_class_h->SetStatus(mirror::Class::kStatusResolved, self); 4452 } 4453 return true; 4454} 4455 4456bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) { 4457 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus()); 4458 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex()); 4459 uint16_t super_class_idx = class_def.superclass_idx_; 4460 if (super_class_idx != DexFile::kDexNoIndex16) { 4461 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get()); 4462 if (super_class == nullptr) { 4463 DCHECK(Thread::Current()->IsExceptionPending()); 4464 return false; 4465 } 4466 // Verify 4467 if (!klass->CanAccess(super_class)) { 4468 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible", 4469 PrettyDescriptor(super_class).c_str(), 4470 PrettyDescriptor(klass.Get()).c_str()); 4471 return false; 4472 } 4473 CHECK(super_class->IsResolved()); 4474 klass->SetSuperClass(super_class); 4475 } 4476 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def); 4477 if (interfaces != nullptr) { 4478 for (size_t i = 0; i < interfaces->Size(); i++) { 4479 uint16_t idx = interfaces->GetTypeItem(i).type_idx_; 4480 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get()); 4481 if (interface == nullptr) { 4482 DCHECK(Thread::Current()->IsExceptionPending()); 4483 return false; 4484 } 4485 // Verify 4486 if (!klass->CanAccess(interface)) { 4487 // TODO: the RI seemed to ignore this in my testing. 4488 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible", 4489 PrettyDescriptor(interface).c_str(), 4490 PrettyDescriptor(klass.Get()).c_str()); 4491 return false; 4492 } 4493 } 4494 } 4495 // Mark the class as loaded. 4496 klass->SetStatus(mirror::Class::kStatusLoaded, nullptr); 4497 return true; 4498} 4499 4500bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) { 4501 CHECK(!klass->IsPrimitive()); 4502 mirror::Class* super = klass->GetSuperClass(); 4503 if (klass.Get() == GetClassRoot(kJavaLangObject)) { 4504 if (super != nullptr) { 4505 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass"); 4506 return false; 4507 } 4508 return true; 4509 } 4510 if (super == nullptr) { 4511 ThrowLinkageError(klass.Get(), "No superclass defined for class %s", 4512 PrettyDescriptor(klass.Get()).c_str()); 4513 return false; 4514 } 4515 // Verify 4516 if (super->IsFinal() || super->IsInterface()) { 4517 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s", 4518 PrettyDescriptor(super).c_str(), 4519 PrettyDescriptor(klass.Get()).c_str(), 4520 super->IsFinal() ? "declared final" : "an interface"); 4521 return false; 4522 } 4523 if (!klass->CanAccess(super)) { 4524 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s", 4525 PrettyDescriptor(super).c_str(), 4526 PrettyDescriptor(klass.Get()).c_str()); 4527 return false; 4528 } 4529 4530 // Inherit kAccClassIsFinalizable from the superclass in case this 4531 // class doesn't override finalize. 4532 if (super->IsFinalizable()) { 4533 klass->SetFinalizable(); 4534 } 4535 4536 // Inherit reference flags (if any) from the superclass. 4537 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask); 4538 if (reference_flags != 0) { 4539 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags); 4540 } 4541 // Disallow custom direct subclasses of java.lang.ref.Reference. 4542 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) { 4543 ThrowLinkageError(klass.Get(), 4544 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed", 4545 PrettyDescriptor(klass.Get()).c_str()); 4546 return false; 4547 } 4548 4549 if (kIsDebugBuild) { 4550 // Ensure super classes are fully resolved prior to resolving fields.. 4551 while (super != nullptr) { 4552 CHECK(super->IsResolved()); 4553 super = super->GetSuperClass(); 4554 } 4555 } 4556 return true; 4557} 4558 4559// Populate the class vtable and itable. Compute return type indices. 4560bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass, 4561 Handle<mirror::ObjectArray<mirror::Class>> interfaces, 4562 StackHandleScope<mirror::Class::kImtSize>* out_imt) { 4563 if (klass->IsInterface()) { 4564 // No vtable. 4565 size_t count = klass->NumVirtualMethods(); 4566 if (!IsUint(16, count)) { 4567 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count); 4568 return false; 4569 } 4570 for (size_t i = 0; i < count; ++i) { 4571 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i); 4572 } 4573 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first. 4574 return false; 4575 } 4576 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last. 4577} 4578 4579// Comparator for name and signature of a method, used in finding overriding methods. Implementation 4580// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex 4581// caches in the implementation below. 4582class MethodNameAndSignatureComparator FINAL { 4583 public: 4584 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method) 4585 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) : 4586 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())), 4587 name_(nullptr), name_len_(0) { 4588 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method); 4589 } 4590 4591 const char* GetName() { 4592 if (name_ == nullptr) { 4593 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_); 4594 } 4595 return name_; 4596 } 4597 4598 bool HasSameNameAndSignature(mirror::ArtMethod* other) 4599 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4600 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other); 4601 const DexFile* other_dex_file = other->GetDexFile(); 4602 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex()); 4603 if (dex_file_ == other_dex_file) { 4604 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_; 4605 } 4606 GetName(); // Only used to make sure its calculated. 4607 uint32_t other_name_len; 4608 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_, 4609 &other_name_len); 4610 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) { 4611 return false; 4612 } 4613 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid); 4614 } 4615 4616 private: 4617 // Dex file for the method to compare against. 4618 const DexFile* const dex_file_; 4619 // MethodId for the method to compare against. 4620 const DexFile::MethodId* const mid_; 4621 // Lazily computed name from the dex file's strings. 4622 const char* name_; 4623 // Lazily computed name length. 4624 uint32_t name_len_; 4625}; 4626 4627class LinkVirtualHashTable { 4628 public: 4629 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table) 4630 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) { 4631 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_); 4632 } 4633 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4634 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index); 4635 const char* name = local_method->GetName(); 4636 uint32_t hash = ComputeModifiedUtf8Hash(name); 4637 uint32_t index = hash % hash_size_; 4638 // Linear probe until we have an empty slot. 4639 while (hash_table_[index] != invalid_index_) { 4640 if (++index == hash_size_) { 4641 index = 0; 4642 } 4643 } 4644 hash_table_[index] = virtual_method_index; 4645 } 4646 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator) 4647 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 4648 const char* name = comparator->GetName(); 4649 uint32_t hash = ComputeModifiedUtf8Hash(name); 4650 size_t index = hash % hash_size_; 4651 while (true) { 4652 const uint32_t value = hash_table_[index]; 4653 // Since linear probe makes continuous blocks, hitting an invalid index means we are done 4654 // the block and can safely assume not found. 4655 if (value == invalid_index_) { 4656 break; 4657 } 4658 if (value != removed_index_) { // This signifies not already overriden. 4659 mirror::ArtMethod* virtual_method = 4660 klass_->GetVirtualMethodDuringLinking(value); 4661 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) { 4662 hash_table_[index] = removed_index_; 4663 return value; 4664 } 4665 } 4666 if (++index == hash_size_) { 4667 index = 0; 4668 } 4669 } 4670 return GetNotFoundIndex(); 4671 } 4672 static uint32_t GetNotFoundIndex() { 4673 return invalid_index_; 4674 } 4675 4676 private: 4677 static const uint32_t invalid_index_; 4678 static const uint32_t removed_index_; 4679 4680 Handle<mirror::Class> klass_; 4681 const size_t hash_size_; 4682 uint32_t* const hash_table_; 4683}; 4684 4685const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max(); 4686const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1; 4687 4688bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) { 4689 const size_t num_virtual_methods = klass->NumVirtualMethods(); 4690 if (klass->HasSuperClass()) { 4691 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength(); 4692 const size_t max_count = num_virtual_methods + super_vtable_length; 4693 StackHandleScope<2> hs(self); 4694 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass())); 4695 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable; 4696 if (super_class->ShouldHaveEmbeddedImtAndVTable()) { 4697 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count)); 4698 if (UNLIKELY(vtable.Get() == nullptr)) { 4699 CHECK(self->IsExceptionPending()); // OOME. 4700 return false; 4701 } 4702 for (size_t i = 0; i < super_vtable_length; i++) { 4703 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i)); 4704 } 4705 if (num_virtual_methods == 0) { 4706 klass->SetVTable(vtable.Get()); 4707 return true; 4708 } 4709 } else { 4710 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable(); 4711 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get()); 4712 if (num_virtual_methods == 0) { 4713 klass->SetVTable(super_vtable); 4714 return true; 4715 } 4716 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count)); 4717 if (UNLIKELY(vtable.Get() == nullptr)) { 4718 CHECK(self->IsExceptionPending()); // OOME. 4719 return false; 4720 } 4721 } 4722 // How the algorithm works: 4723 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash 4724 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual 4725 // method which has not been matched to a vtable method, and j if the virtual method at the 4726 // index overrode the super virtual method at index j. 4727 // 2. Loop through super virtual methods, if they overwrite, update hash table to j 4728 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing 4729 // the need for the initial vtable which we later shrink back down). 4730 // 3. Add non overridden methods to the end of the vtable. 4731 static constexpr size_t kMaxStackHash = 250; 4732 const size_t hash_table_size = num_virtual_methods * 3; 4733 uint32_t* hash_table_ptr; 4734 std::unique_ptr<uint32_t[]> hash_heap_storage; 4735 if (hash_table_size <= kMaxStackHash) { 4736 hash_table_ptr = reinterpret_cast<uint32_t*>( 4737 alloca(hash_table_size * sizeof(*hash_table_ptr))); 4738 } else { 4739 hash_heap_storage.reset(new uint32_t[hash_table_size]); 4740 hash_table_ptr = hash_heap_storage.get(); 4741 } 4742 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr); 4743 // Add virtual methods to the hash table. 4744 for (size_t i = 0; i < num_virtual_methods; ++i) { 4745 hash_table.Add(i); 4746 } 4747 // Loop through each super vtable method and see if they are overriden by a method we added to 4748 // the hash table. 4749 for (size_t j = 0; j < super_vtable_length; ++j) { 4750 // Search the hash table to see if we are overidden by any method. 4751 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j); 4752 MethodNameAndSignatureComparator super_method_name_comparator( 4753 super_method->GetInterfaceMethodIfProxy()); 4754 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator); 4755 if (hash_index != hash_table.GetNotFoundIndex()) { 4756 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index); 4757 if (klass->CanAccessMember(super_method->GetDeclaringClass(), 4758 super_method->GetAccessFlags())) { 4759 if (super_method->IsFinal()) { 4760 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s", 4761 PrettyMethod(virtual_method).c_str(), 4762 super_method->GetDeclaringClassDescriptor()); 4763 return false; 4764 } 4765 vtable->SetWithoutChecks<false>(j, virtual_method); 4766 virtual_method->SetMethodIndex(j); 4767 } else { 4768 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method) 4769 << " would have incorrectly overridden the package-private method in " 4770 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor()); 4771 } 4772 } 4773 } 4774 // Add the non overridden methods at the end. 4775 size_t actual_count = super_vtable_length; 4776 for (size_t i = 0; i < num_virtual_methods; ++i) { 4777 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i); 4778 size_t method_idx = local_method->GetMethodIndexDuringLinking(); 4779 if (method_idx < super_vtable_length && 4780 local_method == vtable->GetWithoutChecks(method_idx)) { 4781 continue; 4782 } 4783 vtable->SetWithoutChecks<false>(actual_count, local_method); 4784 local_method->SetMethodIndex(actual_count); 4785 ++actual_count; 4786 } 4787 if (!IsUint(16, actual_count)) { 4788 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count); 4789 return false; 4790 } 4791 // Shrink vtable if possible 4792 CHECK_LE(actual_count, max_count); 4793 if (actual_count < max_count) { 4794 vtable.Assign(vtable->CopyOf(self, actual_count)); 4795 if (UNLIKELY(vtable.Get() == nullptr)) { 4796 CHECK(self->IsExceptionPending()); // OOME. 4797 return false; 4798 } 4799 } 4800 klass->SetVTable(vtable.Get()); 4801 } else { 4802 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject)); 4803 if (!IsUint(16, num_virtual_methods)) { 4804 ThrowClassFormatError(klass.Get(), "Too many methods: %d", 4805 static_cast<int>(num_virtual_methods)); 4806 return false; 4807 } 4808 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods); 4809 if (UNLIKELY(vtable == nullptr)) { 4810 CHECK(self->IsExceptionPending()); // OOME. 4811 return false; 4812 } 4813 for (size_t i = 0; i < num_virtual_methods; ++i) { 4814 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i); 4815 vtable->SetWithoutChecks<false>(i, virtual_method); 4816 virtual_method->SetMethodIndex(i & 0xFFFF); 4817 } 4818 klass->SetVTable(vtable); 4819 } 4820 return true; 4821} 4822 4823bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass, 4824 Handle<mirror::ObjectArray<mirror::Class>> interfaces, 4825 StackHandleScope<mirror::Class::kImtSize>* out_imt) { 4826 StackHandleScope<2> hs(self); 4827 Runtime* const runtime = Runtime::Current(); 4828 const bool has_superclass = klass->HasSuperClass(); 4829 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U; 4830 const bool have_interfaces = interfaces.Get() != nullptr; 4831 const size_t num_interfaces = 4832 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces(); 4833 if (num_interfaces == 0) { 4834 if (super_ifcount == 0) { 4835 // Class implements no interfaces. 4836 DCHECK_EQ(klass->GetIfTableCount(), 0); 4837 DCHECK(klass->GetIfTable() == nullptr); 4838 return true; 4839 } 4840 // Class implements same interfaces as parent, are any of these not marker interfaces? 4841 bool has_non_marker_interface = false; 4842 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 4843 for (size_t i = 0; i < super_ifcount; ++i) { 4844 if (super_iftable->GetMethodArrayCount(i) > 0) { 4845 has_non_marker_interface = true; 4846 break; 4847 } 4848 } 4849 // Class just inherits marker interfaces from parent so recycle parent's iftable. 4850 if (!has_non_marker_interface) { 4851 klass->SetIfTable(super_iftable); 4852 return true; 4853 } 4854 } 4855 size_t ifcount = super_ifcount + num_interfaces; 4856 for (size_t i = 0; i < num_interfaces; i++) { 4857 mirror::Class* interface = have_interfaces ? 4858 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i); 4859 DCHECK(interface != nullptr); 4860 if (UNLIKELY(!interface->IsInterface())) { 4861 std::string temp; 4862 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s", 4863 PrettyDescriptor(klass.Get()).c_str(), 4864 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str()); 4865 return false; 4866 } 4867 ifcount += interface->GetIfTableCount(); 4868 } 4869 Handle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount))); 4870 if (UNLIKELY(iftable.Get() == nullptr)) { 4871 CHECK(self->IsExceptionPending()); // OOME. 4872 return false; 4873 } 4874 if (super_ifcount != 0) { 4875 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable(); 4876 for (size_t i = 0; i < super_ifcount; i++) { 4877 mirror::Class* super_interface = super_iftable->GetInterface(i); 4878 iftable->SetInterface(i, super_interface); 4879 } 4880 } 4881 // Flatten the interface inheritance hierarchy. 4882 size_t idx = super_ifcount; 4883 for (size_t i = 0; i < num_interfaces; i++) { 4884 mirror::Class* interface = have_interfaces ? interfaces->Get(i) : 4885 mirror::Class::GetDirectInterface(self, klass, i); 4886 // Check if interface is already in iftable 4887 bool duplicate = false; 4888 for (size_t j = 0; j < idx; j++) { 4889 mirror::Class* existing_interface = iftable->GetInterface(j); 4890 if (existing_interface == interface) { 4891 duplicate = true; 4892 break; 4893 } 4894 } 4895 if (!duplicate) { 4896 // Add this non-duplicate interface. 4897 iftable->SetInterface(idx++, interface); 4898 // Add this interface's non-duplicate super-interfaces. 4899 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) { 4900 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j); 4901 bool super_duplicate = false; 4902 for (size_t k = 0; k < idx; k++) { 4903 mirror::Class* existing_interface = iftable->GetInterface(k); 4904 if (existing_interface == super_interface) { 4905 super_duplicate = true; 4906 break; 4907 } 4908 } 4909 if (!super_duplicate) { 4910 iftable->SetInterface(idx++, super_interface); 4911 } 4912 } 4913 } 4914 } 4915 // Shrink iftable in case duplicates were found 4916 if (idx < ifcount) { 4917 DCHECK_NE(num_interfaces, 0U); 4918 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax))); 4919 if (UNLIKELY(iftable.Get() == nullptr)) { 4920 CHECK(self->IsExceptionPending()); // OOME. 4921 return false; 4922 } 4923 ifcount = idx; 4924 } else { 4925 DCHECK_EQ(idx, ifcount); 4926 } 4927 klass->SetIfTable(iftable.Get()); 4928 // If we're an interface, we don't need the vtable pointers, so we're done. 4929 if (klass->IsInterface()) { 4930 return true; 4931 } 4932 Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable( 4933 hs.NewHandle(klass->GetVTableDuringLinking())); 4934 std::vector<mirror::ArtMethod*> miranda_list; 4935 // Copy the IMT from the super class if possible. 4936 bool extend_super_iftable = false; 4937 if (has_superclass) { 4938 mirror::Class* super_class = klass->GetSuperClass(); 4939 extend_super_iftable = true; 4940 if (super_class->ShouldHaveEmbeddedImtAndVTable()) { 4941 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) { 4942 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i)); 4943 } 4944 } else { 4945 // No imt in the super class, need to reconstruct from the iftable. 4946 mirror::IfTable* if_table = super_class->GetIfTable(); 4947 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod(); 4948 const size_t length = super_class->GetIfTableCount(); 4949 for (size_t i = 0; i < length; ++i) { 4950 mirror::Class* interface = iftable->GetInterface(i); 4951 const size_t num_virtuals = interface->NumVirtualMethods(); 4952 const size_t method_array_count = if_table->GetMethodArrayCount(i); 4953 DCHECK_EQ(num_virtuals, method_array_count); 4954 if (method_array_count == 0) { 4955 continue; 4956 } 4957 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i); 4958 for (size_t j = 0; j < num_virtuals; ++j) { 4959 mirror::ArtMethod* method = method_array->GetWithoutChecks(j); 4960 if (method->IsMiranda()) { 4961 continue; 4962 } 4963 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j); 4964 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize; 4965 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod(); 4966 if (imt_ref == runtime->GetImtUnimplementedMethod()) { 4967 out_imt->SetReference(imt_index, method); 4968 } else if (imt_ref != conflict_method) { 4969 out_imt->SetReference(imt_index, conflict_method); 4970 } 4971 } 4972 } 4973 } 4974 } 4975 for (size_t i = 0; i < ifcount; ++i) { 4976 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods(); 4977 if (num_methods > 0) { 4978 StackHandleScope<2> hs(self); 4979 const bool is_super = i < super_ifcount; 4980 const bool super_interface = is_super && extend_super_iftable; 4981 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array; 4982 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array; 4983 if (super_interface) { 4984 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable(); 4985 DCHECK(if_table != nullptr); 4986 DCHECK(if_table->GetMethodArray(i) != nullptr); 4987 // If we are working on a super interface, try extending the existing method array. 4988 method_array = hs.NewHandle(if_table->GetMethodArray(i)->Clone(self)-> 4989 AsObjectArray<mirror::ArtMethod>()); 4990 // We are overwriting a super class interface, try to only virtual methods instead of the 4991 // whole vtable. 4992 input_array = hs.NewHandle(klass->GetVirtualMethods()); 4993 } else { 4994 method_array = hs.NewHandle(AllocArtMethodArray(self, num_methods)); 4995 // A new interface, we need the whole vtable incase a new interface method is implemented 4996 // in the whole superclass. 4997 input_array = vtable; 4998 } 4999 if (UNLIKELY(method_array.Get() == nullptr)) { 5000 CHECK(self->IsExceptionPending()); // OOME. 5001 return false; 5002 } 5003 iftable->SetMethodArray(i, method_array.Get()); 5004 if (input_array.Get() == nullptr) { 5005 // If the added virtual methods is empty, do nothing. 5006 DCHECK(super_interface); 5007 continue; 5008 } 5009 for (size_t j = 0; j < num_methods; ++j) { 5010 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j); 5011 MethodNameAndSignatureComparator interface_name_comparator( 5012 interface_method->GetInterfaceMethodIfProxy()); 5013 int32_t k; 5014 // For each method listed in the interface's method list, find the 5015 // matching method in our class's method list. We want to favor the 5016 // subclass over the superclass, which just requires walking 5017 // back from the end of the vtable. (This only matters if the 5018 // superclass defines a private method and this class redefines 5019 // it -- otherwise it would use the same vtable slot. In .dex files 5020 // those don't end up in the virtual method table, so it shouldn't 5021 // matter which direction we go. We walk it backward anyway.) 5022 for (k = input_array->GetLength() - 1; k >= 0; --k) { 5023 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k); 5024 mirror::ArtMethod* vtable_method_for_name_comparison = 5025 vtable_method->GetInterfaceMethodIfProxy(); 5026 if (interface_name_comparator.HasSameNameAndSignature( 5027 vtable_method_for_name_comparison)) { 5028 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) { 5029 ThrowIllegalAccessError( 5030 klass.Get(), 5031 "Method '%s' implementing interface method '%s' is not public", 5032 PrettyMethod(vtable_method).c_str(), 5033 PrettyMethod(interface_method).c_str()); 5034 return false; 5035 } 5036 method_array->SetWithoutChecks<false>(j, vtable_method); 5037 // Place method in imt if entry is empty, place conflict otherwise. 5038 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize; 5039 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod(); 5040 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod(); 5041 if (imt_ref == runtime->GetImtUnimplementedMethod()) { 5042 out_imt->SetReference(imt_index, vtable_method); 5043 } else if (imt_ref != conflict_method) { 5044 // If we are not a conflict and we have the same signature and name as the imt entry, 5045 // it must be that we overwrote a superclass vtable entry. 5046 MethodNameAndSignatureComparator imt_ref_name_comparator( 5047 imt_ref->GetInterfaceMethodIfProxy()); 5048 if (imt_ref_name_comparator.HasSameNameAndSignature( 5049 vtable_method_for_name_comparison)) { 5050 out_imt->SetReference(imt_index, vtable_method); 5051 } else { 5052 out_imt->SetReference(imt_index, conflict_method); 5053 } 5054 } 5055 break; 5056 } 5057 } 5058 if (k < 0 && !super_interface) { 5059 mirror::ArtMethod* miranda_method = nullptr; 5060 for (mirror::ArtMethod* mir_method : miranda_list) { 5061 if (interface_name_comparator.HasSameNameAndSignature( 5062 mir_method->GetInterfaceMethodIfProxy())) { 5063 miranda_method = mir_method; 5064 break; 5065 } 5066 } 5067 if (miranda_method == nullptr) { 5068 // Point the interface table at a phantom slot. 5069 miranda_method = down_cast<mirror::ArtMethod*>(interface_method->Clone(self)); 5070 if (UNLIKELY(miranda_method == nullptr)) { 5071 CHECK(self->IsExceptionPending()); // OOME. 5072 return false; 5073 } 5074 // TODO: If a methods move then the miranda_list may hold stale references. 5075 miranda_list.push_back(miranda_method); 5076 } 5077 method_array->SetWithoutChecks<false>(j, miranda_method); 5078 } 5079 } 5080 } 5081 } 5082 if (!miranda_list.empty()) { 5083 int old_method_count = klass->NumVirtualMethods(); 5084 int new_method_count = old_method_count + miranda_list.size(); 5085 mirror::ObjectArray<mirror::ArtMethod>* virtuals; 5086 if (old_method_count == 0) { 5087 virtuals = AllocArtMethodArray(self, new_method_count); 5088 } else { 5089 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count); 5090 } 5091 if (UNLIKELY(virtuals == nullptr)) { 5092 CHECK(self->IsExceptionPending()); // OOME. 5093 return false; 5094 } 5095 klass->SetVirtualMethods(virtuals); 5096 5097 int old_vtable_count = vtable->GetLength(); 5098 int new_vtable_count = old_vtable_count + miranda_list.size(); 5099 vtable.Assign(vtable->CopyOf(self, new_vtable_count)); 5100 if (UNLIKELY(vtable.Get() == nullptr)) { 5101 CHECK(self->IsExceptionPending()); // OOME. 5102 return false; 5103 } 5104 for (size_t i = 0; i < miranda_list.size(); ++i) { 5105 mirror::ArtMethod* method = miranda_list[i]; 5106 // Leave the declaring class alone as type indices are relative to it 5107 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda); 5108 method->SetMethodIndex(0xFFFF & (old_vtable_count + i)); 5109 klass->SetVirtualMethod(old_method_count + i, method); 5110 vtable->SetWithoutChecks<false>(old_vtable_count + i, method); 5111 } 5112 // TODO: do not assign to the vtable field until it is fully constructed. 5113 klass->SetVTable(vtable.Get()); 5114 } 5115 5116 if (kIsDebugBuild) { 5117 mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking(); 5118 for (int i = 0; i < vtable->GetLength(); ++i) { 5119 CHECK(vtable->GetWithoutChecks(i) != nullptr); 5120 } 5121 } 5122 5123 return true; 5124} 5125 5126bool ClassLinker::LinkInstanceFields(Handle<mirror::Class> klass) { 5127 CHECK(klass.Get() != nullptr); 5128 return LinkFields(klass, false, nullptr); 5129} 5130 5131bool ClassLinker::LinkStaticFields(Handle<mirror::Class> klass, size_t* class_size) { 5132 CHECK(klass.Get() != nullptr); 5133 return LinkFields(klass, true, class_size); 5134} 5135 5136struct LinkFieldsComparator { 5137 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 5138 } 5139 // No thread safety analysis as will be called from STL. Checked lock held in constructor. 5140 bool operator()(mirror::ArtField* field1, mirror::ArtField* field2) 5141 NO_THREAD_SAFETY_ANALYSIS { 5142 // First come reference fields, then 64-bit, and finally 32-bit 5143 Primitive::Type type1 = field1->GetTypeAsPrimitiveType(); 5144 Primitive::Type type2 = field2->GetTypeAsPrimitiveType(); 5145 if (type1 != type2) { 5146 bool is_primitive1 = type1 != Primitive::kPrimNot; 5147 bool is_primitive2 = type2 != Primitive::kPrimNot; 5148 bool is64bit1 = is_primitive1 && (type1 == Primitive::kPrimLong || 5149 type1 == Primitive::kPrimDouble); 5150 bool is64bit2 = is_primitive2 && (type2 == Primitive::kPrimLong || 5151 type2 == Primitive::kPrimDouble); 5152 int order1 = !is_primitive1 ? 0 : (is64bit1 ? 1 : 2); 5153 int order2 = !is_primitive2 ? 0 : (is64bit2 ? 1 : 2); 5154 if (order1 != order2) { 5155 return order1 < order2; 5156 } 5157 } 5158 // same basic group? then sort by string. 5159 return strcmp(field1->GetName(), field2->GetName()) < 0; 5160 } 5161}; 5162 5163bool ClassLinker::LinkFields(Handle<mirror::Class> klass, bool is_static, size_t* class_size) { 5164 size_t num_fields = 5165 is_static ? klass->NumStaticFields() : klass->NumInstanceFields(); 5166 5167 mirror::ObjectArray<mirror::ArtField>* fields = 5168 is_static ? klass->GetSFields() : klass->GetIFields(); 5169 5170 // Initialize field_offset 5171 MemberOffset field_offset(0); 5172 if (is_static) { 5173 uint32_t base = sizeof(mirror::Class); // Static fields come after the class. 5174 if (klass->ShouldHaveEmbeddedImtAndVTable()) { 5175 // Static fields come after the embedded tables. 5176 base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(), 5177 0, 0, 0); 5178 } 5179 field_offset = MemberOffset(base); 5180 } else { 5181 mirror::Class* super_class = klass->GetSuperClass(); 5182 if (super_class != nullptr) { 5183 CHECK(super_class->IsResolved()) 5184 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class); 5185 field_offset = MemberOffset(super_class->GetObjectSize()); 5186 } 5187 } 5188 5189 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get()); 5190 5191 // we want a relatively stable order so that adding new fields 5192 // minimizes disruption of C++ version such as Class and Method. 5193 std::deque<mirror::ArtField*> grouped_and_sorted_fields; 5194 for (size_t i = 0; i < num_fields; i++) { 5195 mirror::ArtField* f = fields->Get(i); 5196 CHECK(f != nullptr) << PrettyClass(klass.Get()); 5197 grouped_and_sorted_fields.push_back(f); 5198 } 5199 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(), 5200 LinkFieldsComparator()); 5201 5202 // References should be at the front. 5203 size_t current_field = 0; 5204 size_t num_reference_fields = 0; 5205 for (; current_field < num_fields; current_field++) { 5206 mirror::ArtField* field = grouped_and_sorted_fields.front(); 5207 Primitive::Type type = field->GetTypeAsPrimitiveType(); 5208 bool isPrimitive = type != Primitive::kPrimNot; 5209 if (isPrimitive) { 5210 break; // past last reference, move on to the next phase 5211 } 5212 grouped_and_sorted_fields.pop_front(); 5213 num_reference_fields++; 5214 fields->Set<false>(current_field, field); 5215 field->SetOffset(field_offset); 5216 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t)); 5217 } 5218 5219 // Now we want to pack all of the double-wide fields together. If 5220 // we're not aligned, though, we want to shuffle one 32-bit field 5221 // into place. If we can't find one, we'll have to pad it. 5222 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) { 5223 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) { 5224 mirror::ArtField* field = grouped_and_sorted_fields[i]; 5225 Primitive::Type type = field->GetTypeAsPrimitiveType(); 5226 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types 5227 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) { 5228 continue; 5229 } 5230 fields->Set<false>(current_field++, field); 5231 field->SetOffset(field_offset); 5232 // drop the consumed field 5233 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i); 5234 break; 5235 } 5236 // whether we found a 32-bit field for padding or not, we advance 5237 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t)); 5238 } 5239 5240 // Alignment is good, shuffle any double-wide fields forward, and 5241 // finish assigning field offsets to all fields. 5242 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value())) 5243 << PrettyClass(klass.Get()); 5244 while (!grouped_and_sorted_fields.empty()) { 5245 mirror::ArtField* field = grouped_and_sorted_fields.front(); 5246 grouped_and_sorted_fields.pop_front(); 5247 Primitive::Type type = field->GetTypeAsPrimitiveType(); 5248 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types 5249 fields->Set<false>(current_field, field); 5250 field->SetOffset(field_offset); 5251 field_offset = MemberOffset(field_offset.Uint32Value() + 5252 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble) 5253 ? sizeof(uint64_t) 5254 : sizeof(uint32_t))); 5255 current_field++; 5256 } 5257 5258 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it. 5259 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) { 5260 // We know there are no non-reference fields in the Reference classes, and we know 5261 // that 'referent' is alphabetically last, so this is easy... 5262 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get()); 5263 CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get()); 5264 --num_reference_fields; 5265 } 5266 5267 if (kIsDebugBuild) { 5268 // Make sure that all reference fields appear before 5269 // non-reference fields, and all double-wide fields are aligned. 5270 bool seen_non_ref = false; 5271 for (size_t i = 0; i < num_fields; i++) { 5272 mirror::ArtField* field = fields->Get(i); 5273 if (false) { // enable to debug field layout 5274 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance") 5275 << " class=" << PrettyClass(klass.Get()) 5276 << " field=" << PrettyField(field) 5277 << " offset=" 5278 << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset())); 5279 } 5280 Primitive::Type type = field->GetTypeAsPrimitiveType(); 5281 bool is_primitive = type != Primitive::kPrimNot; 5282 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") && 5283 strcmp("referent", field->GetName()) == 0) { 5284 is_primitive = true; // We lied above, so we have to expect a lie here. 5285 } 5286 if (is_primitive) { 5287 if (!seen_non_ref) { 5288 seen_non_ref = true; 5289 DCHECK_EQ(num_reference_fields, i) << PrettyField(field); 5290 } 5291 } else { 5292 DCHECK(!seen_non_ref) << PrettyField(field); 5293 } 5294 } 5295 if (!seen_non_ref) { 5296 DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get()); 5297 } 5298 } 5299 5300 size_t size = field_offset.Uint32Value(); 5301 // Update klass 5302 if (is_static) { 5303 klass->SetNumReferenceStaticFields(num_reference_fields); 5304 *class_size = size; 5305 } else { 5306 klass->SetNumReferenceInstanceFields(num_reference_fields); 5307 if (!klass->IsVariableSize()) { 5308 std::string temp; 5309 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp); 5310 size_t previous_size = klass->GetObjectSize(); 5311 if (previous_size != 0) { 5312 // Make sure that we didn't originally have an incorrect size. 5313 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp); 5314 } 5315 klass->SetObjectSize(size); 5316 } 5317 } 5318 return true; 5319} 5320 5321// Set the bitmap of reference offsets, refOffsets, from the ifields 5322// list. 5323void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) { 5324 uint32_t reference_offsets = 0; 5325 mirror::Class* super_class = klass->GetSuperClass(); 5326 if (super_class != nullptr) { 5327 reference_offsets = super_class->GetReferenceInstanceOffsets(); 5328 // If our superclass overflowed, we don't stand a chance. 5329 if (reference_offsets == CLASS_WALK_SUPER) { 5330 klass->SetReferenceInstanceOffsets(reference_offsets); 5331 return; 5332 } 5333 } 5334 CreateReferenceOffsets(klass, false, reference_offsets); 5335} 5336 5337void ClassLinker::CreateReferenceStaticOffsets(Handle<mirror::Class> klass) { 5338 CreateReferenceOffsets(klass, true, 0); 5339} 5340 5341void ClassLinker::CreateReferenceOffsets(Handle<mirror::Class> klass, bool is_static, 5342 uint32_t reference_offsets) { 5343 size_t num_reference_fields = 5344 is_static ? klass->NumReferenceStaticFieldsDuringLinking() 5345 : klass->NumReferenceInstanceFieldsDuringLinking(); 5346 mirror::ObjectArray<mirror::ArtField>* fields = 5347 is_static ? klass->GetSFields() : klass->GetIFields(); 5348 // All of the fields that contain object references are guaranteed 5349 // to be at the beginning of the fields list. 5350 for (size_t i = 0; i < num_reference_fields; ++i) { 5351 // Note that byte_offset is the offset from the beginning of 5352 // object, not the offset into instance data 5353 mirror::ArtField* field = fields->Get(i); 5354 MemberOffset byte_offset = field->GetOffsetDuringLinking(); 5355 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U); 5356 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) { 5357 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value()); 5358 CHECK_NE(new_bit, 0U); 5359 reference_offsets |= new_bit; 5360 } else { 5361 reference_offsets = CLASS_WALK_SUPER; 5362 break; 5363 } 5364 } 5365 // Update fields in klass 5366 if (is_static) { 5367 klass->SetReferenceStaticOffsets(reference_offsets); 5368 } else { 5369 klass->SetReferenceInstanceOffsets(reference_offsets); 5370 } 5371} 5372 5373mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx, 5374 Handle<mirror::DexCache> dex_cache) { 5375 DCHECK(dex_cache.Get() != nullptr); 5376 mirror::String* resolved = dex_cache->GetResolvedString(string_idx); 5377 if (resolved != nullptr) { 5378 return resolved; 5379 } 5380 uint32_t utf16_length; 5381 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length); 5382 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data); 5383 dex_cache->SetResolvedString(string_idx, string); 5384 return string; 5385} 5386 5387mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx, 5388 mirror::Class* referrer) { 5389 StackHandleScope<2> hs(Thread::Current()); 5390 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache())); 5391 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader())); 5392 return ResolveType(dex_file, type_idx, dex_cache, class_loader); 5393} 5394 5395mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx, 5396 Handle<mirror::DexCache> dex_cache, 5397 Handle<mirror::ClassLoader> class_loader) { 5398 DCHECK(dex_cache.Get() != nullptr); 5399 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx); 5400 if (resolved == nullptr) { 5401 Thread* self = Thread::Current(); 5402 const char* descriptor = dex_file.StringByTypeIdx(type_idx); 5403 resolved = FindClass(self, descriptor, class_loader); 5404 if (resolved != nullptr) { 5405 // TODO: we used to throw here if resolved's class loader was not the 5406 // boot class loader. This was to permit different classes with the 5407 // same name to be loaded simultaneously by different loaders 5408 dex_cache->SetResolvedType(type_idx, resolved); 5409 } else { 5410 CHECK(self->IsExceptionPending()) 5411 << "Expected pending exception for failed resolution of: " << descriptor; 5412 // Convert a ClassNotFoundException to a NoClassDefFoundError. 5413 StackHandleScope<1> hs(self); 5414 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr))); 5415 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) { 5416 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved. 5417 self->ClearException(); 5418 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor); 5419 self->GetException(nullptr)->SetCause(cause.Get()); 5420 } 5421 } 5422 } 5423 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous()) 5424 << PrettyDescriptor(resolved) << " " << resolved->GetStatus(); 5425 return resolved; 5426} 5427 5428mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx, 5429 Handle<mirror::DexCache> dex_cache, 5430 Handle<mirror::ClassLoader> class_loader, 5431 Handle<mirror::ArtMethod> referrer, 5432 InvokeType type) { 5433 DCHECK(dex_cache.Get() != nullptr); 5434 // Check for hit in the dex cache. 5435 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx); 5436 if (resolved != nullptr && !resolved->IsRuntimeMethod()) { 5437 return resolved; 5438 } 5439 // Fail, get the declaring class. 5440 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 5441 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader); 5442 if (klass == nullptr) { 5443 DCHECK(Thread::Current()->IsExceptionPending()); 5444 return nullptr; 5445 } 5446 // Scan using method_idx, this saves string compares but will only hit for matching dex 5447 // caches/files. 5448 switch (type) { 5449 case kDirect: // Fall-through. 5450 case kStatic: 5451 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx); 5452 break; 5453 case kInterface: 5454 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx); 5455 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface()); 5456 break; 5457 case kSuper: // Fall-through. 5458 case kVirtual: 5459 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx); 5460 break; 5461 default: 5462 LOG(FATAL) << "Unreachable - invocation type: " << type; 5463 } 5464 if (resolved == nullptr) { 5465 // Search by name, which works across dex files. 5466 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 5467 const Signature signature = dex_file.GetMethodSignature(method_id); 5468 switch (type) { 5469 case kDirect: // Fall-through. 5470 case kStatic: 5471 resolved = klass->FindDirectMethod(name, signature); 5472 break; 5473 case kInterface: 5474 resolved = klass->FindInterfaceMethod(name, signature); 5475 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface()); 5476 break; 5477 case kSuper: // Fall-through. 5478 case kVirtual: 5479 resolved = klass->FindVirtualMethod(name, signature); 5480 break; 5481 } 5482 } 5483 // If we found a method, check for incompatible class changes. 5484 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) { 5485 // Be a good citizen and update the dex cache to speed subsequent calls. 5486 dex_cache->SetResolvedMethod(method_idx, resolved); 5487 return resolved; 5488 } else { 5489 // If we had a method, it's an incompatible-class-change error. 5490 if (resolved != nullptr) { 5491 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get()); 5492 } else { 5493 // We failed to find the method which means either an access error, an incompatible class 5494 // change, or no such method. First try to find the method among direct and virtual methods. 5495 const char* name = dex_file.StringDataByIdx(method_id.name_idx_); 5496 const Signature signature = dex_file.GetMethodSignature(method_id); 5497 switch (type) { 5498 case kDirect: 5499 case kStatic: 5500 resolved = klass->FindVirtualMethod(name, signature); 5501 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would 5502 // have had a resolved method before, which triggers the "true" branch above. 5503 break; 5504 case kInterface: 5505 case kVirtual: 5506 case kSuper: 5507 resolved = klass->FindDirectMethod(name, signature); 5508 break; 5509 } 5510 5511 // If we found something, check that it can be accessed by the referrer. 5512 if (resolved != nullptr && referrer.Get() != nullptr) { 5513 mirror::Class* methods_class = resolved->GetDeclaringClass(); 5514 mirror::Class* referring_class = referrer->GetDeclaringClass(); 5515 if (!referring_class->CanAccess(methods_class)) { 5516 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class, 5517 resolved, type); 5518 return nullptr; 5519 } else if (!referring_class->CanAccessMember(methods_class, 5520 resolved->GetAccessFlags())) { 5521 ThrowIllegalAccessErrorMethod(referring_class, resolved); 5522 return nullptr; 5523 } 5524 } 5525 5526 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface 5527 // methods and throw if we find the method there. If we find nothing, throw a 5528 // NoSuchMethodError. 5529 switch (type) { 5530 case kDirect: 5531 case kStatic: 5532 if (resolved != nullptr) { 5533 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get()); 5534 } else { 5535 resolved = klass->FindInterfaceMethod(name, signature); 5536 if (resolved != nullptr) { 5537 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get()); 5538 } else { 5539 ThrowNoSuchMethodError(type, klass, name, signature); 5540 } 5541 } 5542 break; 5543 case kInterface: 5544 if (resolved != nullptr) { 5545 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get()); 5546 } else { 5547 resolved = klass->FindVirtualMethod(name, signature); 5548 if (resolved != nullptr) { 5549 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get()); 5550 } else { 5551 ThrowNoSuchMethodError(type, klass, name, signature); 5552 } 5553 } 5554 break; 5555 case kSuper: 5556 if (resolved != nullptr) { 5557 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get()); 5558 } else { 5559 ThrowNoSuchMethodError(type, klass, name, signature); 5560 } 5561 break; 5562 case kVirtual: 5563 if (resolved != nullptr) { 5564 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get()); 5565 } else { 5566 resolved = klass->FindInterfaceMethod(name, signature); 5567 if (resolved != nullptr) { 5568 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get()); 5569 } else { 5570 ThrowNoSuchMethodError(type, klass, name, signature); 5571 } 5572 } 5573 break; 5574 } 5575 } 5576 DCHECK(Thread::Current()->IsExceptionPending()); 5577 return nullptr; 5578 } 5579} 5580 5581mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx, 5582 Handle<mirror::DexCache> dex_cache, 5583 Handle<mirror::ClassLoader> class_loader, 5584 bool is_static) { 5585 DCHECK(dex_cache.Get() != nullptr); 5586 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx); 5587 if (resolved != nullptr) { 5588 return resolved; 5589 } 5590 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 5591 Thread* const self = Thread::Current(); 5592 StackHandleScope<1> hs(self); 5593 Handle<mirror::Class> klass( 5594 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader))); 5595 if (klass.Get() == nullptr) { 5596 DCHECK(Thread::Current()->IsExceptionPending()); 5597 return nullptr; 5598 } 5599 5600 if (is_static) { 5601 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx); 5602 } else { 5603 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx); 5604 } 5605 5606 if (resolved == nullptr) { 5607 const char* name = dex_file.GetFieldName(field_id); 5608 const char* type = dex_file.GetFieldTypeDescriptor(field_id); 5609 if (is_static) { 5610 resolved = mirror::Class::FindStaticField(self, klass, name, type); 5611 } else { 5612 resolved = klass->FindInstanceField(name, type); 5613 } 5614 if (resolved == nullptr) { 5615 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name); 5616 return nullptr; 5617 } 5618 } 5619 dex_cache->SetResolvedField(field_idx, resolved); 5620 return resolved; 5621} 5622 5623mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, 5624 uint32_t field_idx, 5625 Handle<mirror::DexCache> dex_cache, 5626 Handle<mirror::ClassLoader> class_loader) { 5627 DCHECK(dex_cache.Get() != nullptr); 5628 mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx); 5629 if (resolved != nullptr) { 5630 return resolved; 5631 } 5632 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx); 5633 Thread* self = Thread::Current(); 5634 StackHandleScope<1> hs(self); 5635 Handle<mirror::Class> klass( 5636 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader))); 5637 if (klass.Get() == nullptr) { 5638 DCHECK(Thread::Current()->IsExceptionPending()); 5639 return nullptr; 5640 } 5641 5642 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_)); 5643 StringPiece type(dex_file.StringDataByIdx( 5644 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_)); 5645 resolved = mirror::Class::FindField(self, klass, name, type); 5646 if (resolved != nullptr) { 5647 dex_cache->SetResolvedField(field_idx, resolved); 5648 } else { 5649 ThrowNoSuchFieldError("", klass.Get(), type, name); 5650 } 5651 return resolved; 5652} 5653 5654const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer, 5655 uint32_t* length) { 5656 mirror::Class* declaring_class = referrer->GetDeclaringClass(); 5657 mirror::DexCache* dex_cache = declaring_class->GetDexCache(); 5658 const DexFile& dex_file = *dex_cache->GetDexFile(); 5659 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx); 5660 return dex_file.GetMethodShorty(method_id, length); 5661} 5662 5663void ClassLinker::DumpAllClasses(int flags) { 5664 if (dex_cache_image_class_lookup_required_) { 5665 MoveImageClassesToClassTable(); 5666 } 5667 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker 5668 // lock held, because it might need to resolve a field's type, which would try to take the lock. 5669 std::vector<mirror::Class*> all_classes; 5670 { 5671 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 5672 for (GcRoot<mirror::Class>& it : class_table_) { 5673 all_classes.push_back(it.Read()); 5674 } 5675 } 5676 5677 for (size_t i = 0; i < all_classes.size(); ++i) { 5678 all_classes[i]->DumpClass(std::cerr, flags); 5679 } 5680} 5681 5682void ClassLinker::DumpForSigQuit(std::ostream& os) { 5683 if (dex_cache_image_class_lookup_required_) { 5684 MoveImageClassesToClassTable(); 5685 } 5686 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 5687 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes=" 5688 << class_table_.Size() << "\n"; 5689} 5690 5691size_t ClassLinker::NumLoadedClasses() { 5692 if (dex_cache_image_class_lookup_required_) { 5693 MoveImageClassesToClassTable(); 5694 } 5695 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_); 5696 // Only return non zygote classes since these are the ones which apps which care about. 5697 return class_table_.Size(); 5698} 5699 5700pid_t ClassLinker::GetClassesLockOwner() { 5701 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid(); 5702} 5703 5704pid_t ClassLinker::GetDexLockOwner() { 5705 return dex_lock_.GetExclusiveOwnerTid(); 5706} 5707 5708void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) { 5709 DCHECK(!init_done_); 5710 5711 DCHECK(klass != nullptr); 5712 DCHECK(klass->GetClassLoader() == nullptr); 5713 5714 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read(); 5715 DCHECK(class_roots != nullptr); 5716 DCHECK(class_roots->Get(class_root) == nullptr); 5717 class_roots->Set<false>(class_root, klass); 5718} 5719 5720std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root) 5721 const { 5722 std::string temp; 5723 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp)); 5724} 5725 5726bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a, 5727 const GcRoot<mirror::Class>& b) { 5728 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) { 5729 return false; 5730 } 5731 std::string temp; 5732 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp)); 5733} 5734 5735std::size_t ClassLinker::ClassDescriptorHashEquals::operator()( 5736 const std::pair<const char*, mirror::ClassLoader*>& element) const { 5737 return ComputeModifiedUtf8Hash(element.first); 5738} 5739 5740bool ClassLinker::ClassDescriptorHashEquals::operator()( 5741 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) { 5742 if (a.Read()->GetClassLoader() != b.second) { 5743 return false; 5744 } 5745 return a.Read()->DescriptorEquals(b.first); 5746} 5747 5748bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a, 5749 const char* descriptor) { 5750 return a.Read()->DescriptorEquals(descriptor); 5751} 5752 5753std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const { 5754 return ComputeModifiedUtf8Hash(descriptor); 5755} 5756 5757} // namespace art 5758