1 /* Copyright (C) 2016 The Android Open Source Project 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 * 4 * This file implements interfaces from the file jvmti.h. This implementation 5 * is licensed under the same terms as the file jvmti.h. The 6 * copyright and license information for the file jvmti.h follows. 7 * 8 * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. 9 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 10 * 11 * This code is free software; you can redistribute it and/or modify it 12 * under the terms of the GNU General Public License version 2 only, as 13 * published by the Free Software Foundation. Oracle designates this 14 * particular file as subject to the "Classpath" exception as provided 15 * by Oracle in the LICENSE file that accompanied this code. 16 * 17 * This code is distributed in the hope that it will be useful, but WITHOUT 18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 20 * version 2 for more details (a copy is included in the LICENSE file that 21 * accompanied this code). 22 * 23 * You should have received a copy of the GNU General Public License version 24 * 2 along with this work; if not, write to the Free Software Foundation, 25 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 26 * 27 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 28 * or visit www.oracle.com if you need additional information or have any 29 * questions. 30 */ 31 32 #include "ti_redefine.h" 33 34 #include <limits> 35 36 #include "android-base/stringprintf.h" 37 38 #include "art_field-inl.h" 39 #include "art_method-inl.h" 40 #include "art_jvmti.h" 41 #include "base/array_slice.h" 42 #include "base/logging.h" 43 #include "class_linker-inl.h" 44 #include "debugger.h" 45 #include "dex_file.h" 46 #include "dex_file_types.h" 47 #include "events-inl.h" 48 #include "gc/allocation_listener.h" 49 #include "gc/heap.h" 50 #include "instrumentation.h" 51 #include "jdwp/jdwp.h" 52 #include "jdwp/jdwp_constants.h" 53 #include "jdwp/jdwp_event.h" 54 #include "jdwp/object_registry.h" 55 #include "jit/jit.h" 56 #include "jit/jit_code_cache.h" 57 #include "jni_env_ext-inl.h" 58 #include "jvmti_allocator.h" 59 #include "mirror/class-inl.h" 60 #include "mirror/class_ext.h" 61 #include "mirror/object.h" 62 #include "non_debuggable_classes.h" 63 #include "object_lock.h" 64 #include "runtime.h" 65 #include "ScopedLocalRef.h" 66 #include "ti_class_loader.h" 67 #include "transform.h" 68 #include "verifier/method_verifier.h" 69 #include "verifier/verifier_enums.h" 70 71 namespace openjdkjvmti { 72 73 using android::base::StringPrintf; 74 75 // A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as 76 // they are created. This ensures that we can always call any method of an obsolete ArtMethod object 77 // almost as soon as they are created since the GetObsoleteDexCache method will succeed. 78 class ObsoleteMap { 79 public: 80 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original) 81 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) { 82 auto method_pair = id_map_.find(original); 83 if (method_pair != id_map_.end()) { 84 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>( 85 method_pair->second, art::kRuntimePointerSize); 86 DCHECK(res != nullptr); 87 DCHECK_EQ(original, res->GetNonObsoleteMethod()); 88 return res; 89 } else { 90 return nullptr; 91 } 92 } 93 94 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete) 95 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) { 96 DCHECK(original != nullptr); 97 DCHECK(obsolete != nullptr); 98 int32_t slot = next_free_slot_++; 99 DCHECK_LT(slot, obsolete_methods_->GetLength()); 100 DCHECK(nullptr == 101 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize)); 102 DCHECK(nullptr == obsolete_dex_caches_->Get(slot)); 103 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize); 104 obsolete_dex_caches_->Set(slot, original_dex_cache_); 105 id_map_.insert({original, slot}); 106 } 107 108 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods, 109 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches, 110 art::ObjPtr<art::mirror::DexCache> original_dex_cache) 111 : next_free_slot_(0), 112 obsolete_methods_(obsolete_methods), 113 obsolete_dex_caches_(obsolete_dex_caches), 114 original_dex_cache_(original_dex_cache) { 115 // Figure out where the first unused slot in the obsolete_methods_ array is. 116 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>( 117 next_free_slot_, art::kRuntimePointerSize) != nullptr) { 118 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr); 119 next_free_slot_++; 120 } 121 // Sanity check that the same slot in obsolete_dex_caches_ is free. 122 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr); 123 } 124 125 private: 126 int32_t next_free_slot_; 127 std::unordered_map<art::ArtMethod*, int32_t> id_map_; 128 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used 129 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended). 130 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_; 131 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_; 132 art::ObjPtr<art::mirror::DexCache> original_dex_cache_; 133 }; 134 135 // This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does 136 // some basic sanity checks that the obsolete method is sane. 137 class ObsoleteMethodStackVisitor : public art::StackVisitor { 138 protected: 139 ObsoleteMethodStackVisitor( 140 art::Thread* thread, 141 art::LinearAlloc* allocator, 142 const std::unordered_set<art::ArtMethod*>& obsoleted_methods, 143 ObsoleteMap* obsolete_maps) 144 : StackVisitor(thread, 145 /*context*/nullptr, 146 StackVisitor::StackWalkKind::kIncludeInlinedFrames), 147 allocator_(allocator), 148 obsoleted_methods_(obsoleted_methods), 149 obsolete_maps_(obsolete_maps) { } 150 151 ~ObsoleteMethodStackVisitor() OVERRIDE {} 152 153 public: 154 // Returns true if we successfully installed obsolete methods on this thread, filling 155 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail. 156 // The stack is cleaned up when we fail. 157 static void UpdateObsoleteFrames( 158 art::Thread* thread, 159 art::LinearAlloc* allocator, 160 const std::unordered_set<art::ArtMethod*>& obsoleted_methods, 161 ObsoleteMap* obsolete_maps) 162 REQUIRES(art::Locks::mutator_lock_) { 163 ObsoleteMethodStackVisitor visitor(thread, 164 allocator, 165 obsoleted_methods, 166 obsolete_maps); 167 visitor.WalkStack(); 168 } 169 170 bool VisitFrame() OVERRIDE REQUIRES(art::Locks::mutator_lock_) { 171 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods."); 172 art::ArtMethod* old_method = GetMethod(); 173 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) { 174 // We cannot ensure that the right dex file is used in inlined frames so we don't support 175 // redefining them. 176 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition"; 177 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method); 178 if (new_obsolete_method == nullptr) { 179 // Create a new Obsolete Method and put it in the list. 180 art::Runtime* runtime = art::Runtime::Current(); 181 art::ClassLinker* cl = runtime->GetClassLinker(); 182 auto ptr_size = cl->GetImagePointerSize(); 183 const size_t method_size = art::ArtMethod::Size(ptr_size); 184 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size); 185 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '" 186 << old_method->PrettyMethod() << "'"; 187 new_obsolete_method = new (method_storage) art::ArtMethod(); 188 new_obsolete_method->CopyFrom(old_method, ptr_size); 189 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass()); 190 new_obsolete_method->SetIsObsolete(); 191 new_obsolete_method->SetDontCompile(); 192 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method); 193 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method); 194 // Update JIT Data structures to point to the new method. 195 art::jit::Jit* jit = art::Runtime::Current()->GetJit(); 196 if (jit != nullptr) { 197 // Notify the JIT we are making this obsolete method. It will update the jit's internal 198 // structures to keep track of the new obsolete method. 199 jit->GetCodeCache()->MoveObsoleteMethod(old_method, new_obsolete_method); 200 } 201 } 202 DCHECK(new_obsolete_method != nullptr); 203 SetMethod(new_obsolete_method); 204 } 205 return true; 206 } 207 208 private: 209 // The linear allocator we should use to make new methods. 210 art::LinearAlloc* allocator_; 211 // The set of all methods which could be obsoleted. 212 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_; 213 // A map from the original to the newly allocated obsolete method for frames on this thread. The 214 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of 215 // the redefined classes ClassExt as it is filled. 216 ObsoleteMap* obsolete_maps_; 217 }; 218 219 jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED, 220 jclass klass, 221 jboolean* is_redefinable) { 222 art::Thread* self = art::Thread::Current(); 223 art::ScopedObjectAccess soa(self); 224 art::StackHandleScope<1> hs(self); 225 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass)); 226 if (obj.IsNull()) { 227 return ERR(INVALID_CLASS); 228 } 229 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass())); 230 std::string err_unused; 231 *is_redefinable = 232 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) == OK ? JNI_TRUE : JNI_FALSE; 233 return OK; 234 } 235 236 jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass, 237 /*out*/std::string* error_msg) { 238 if (klass->IsPrimitive()) { 239 *error_msg = "Modification of primitive classes is not supported"; 240 return ERR(UNMODIFIABLE_CLASS); 241 } else if (klass->IsInterface()) { 242 *error_msg = "Modification of Interface classes is currently not supported"; 243 return ERR(UNMODIFIABLE_CLASS); 244 } else if (klass->IsStringClass()) { 245 *error_msg = "Modification of String class is not supported"; 246 return ERR(UNMODIFIABLE_CLASS); 247 } else if (klass->IsArrayClass()) { 248 *error_msg = "Modification of Array classes is not supported"; 249 return ERR(UNMODIFIABLE_CLASS); 250 } else if (klass->IsProxyClass()) { 251 *error_msg = "Modification of proxy classes is not supported"; 252 return ERR(UNMODIFIABLE_CLASS); 253 } 254 255 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) { 256 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) { 257 *error_msg = "Class might have stack frames that cannot be made obsolete"; 258 return ERR(UNMODIFIABLE_CLASS); 259 } 260 } 261 262 return OK; 263 } 264 265 // Moves dex data to an anonymous, read-only mmap'd region. 266 std::unique_ptr<art::MemMap> Redefiner::MoveDataToMemMap(const std::string& original_location, 267 art::ArraySlice<const unsigned char> data, 268 std::string* error_msg) { 269 std::unique_ptr<art::MemMap> map(art::MemMap::MapAnonymous( 270 StringPrintf("%s-transformed", original_location.c_str()).c_str(), 271 nullptr, 272 data.size(), 273 PROT_READ|PROT_WRITE, 274 /*low_4gb*/false, 275 /*reuse*/false, 276 error_msg)); 277 if (map == nullptr) { 278 return map; 279 } 280 memcpy(map->Begin(), &data.At(0), data.size()); 281 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents 282 // programs from corrupting it. 283 map->Protect(PROT_READ); 284 return map; 285 } 286 287 Redefiner::ClassRedefinition::ClassRedefinition( 288 Redefiner* driver, 289 jclass klass, 290 const art::DexFile* redefined_dex_file, 291 const char* class_sig, 292 art::ArraySlice<const unsigned char> orig_dex_file) : 293 driver_(driver), 294 klass_(klass), 295 dex_file_(redefined_dex_file), 296 class_sig_(class_sig), 297 original_dex_file_(orig_dex_file) { 298 GetMirrorClass()->MonitorEnter(driver_->self_); 299 } 300 301 Redefiner::ClassRedefinition::~ClassRedefinition() { 302 if (driver_ != nullptr) { 303 GetMirrorClass()->MonitorExit(driver_->self_); 304 } 305 } 306 307 jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env, 308 EventHandler* event_handler, 309 art::Runtime* runtime, 310 art::Thread* self, 311 jint class_count, 312 const jvmtiClassDefinition* definitions, 313 /*out*/std::string* error_msg) { 314 if (env == nullptr) { 315 *error_msg = "env was null!"; 316 return ERR(INVALID_ENVIRONMENT); 317 } else if (class_count < 0) { 318 *error_msg = "class_count was less then 0"; 319 return ERR(ILLEGAL_ARGUMENT); 320 } else if (class_count == 0) { 321 // We don't actually need to do anything. Just return OK. 322 return OK; 323 } else if (definitions == nullptr) { 324 *error_msg = "null definitions!"; 325 return ERR(NULL_POINTER); 326 } 327 std::vector<ArtClassDefinition> def_vector; 328 def_vector.reserve(class_count); 329 for (jint i = 0; i < class_count; i++) { 330 jboolean is_modifiable = JNI_FALSE; 331 jvmtiError res = env->IsModifiableClass(definitions[i].klass, &is_modifiable); 332 if (res != OK) { 333 return res; 334 } else if (!is_modifiable) { 335 return ERR(UNMODIFIABLE_CLASS); 336 } 337 // We make a copy of the class_bytes to pass into the retransformation. 338 // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we 339 // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls 340 // to get the passed in bytes. 341 unsigned char* class_bytes_copy = nullptr; 342 res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy); 343 if (res != OK) { 344 return res; 345 } 346 memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count); 347 348 ArtClassDefinition def; 349 res = def.Init(env, definitions[i]); 350 if (res != OK) { 351 return res; 352 } 353 def_vector.push_back(std::move(def)); 354 } 355 // Call all the transformation events. 356 jvmtiError res = Transformer::RetransformClassesDirect(env, 357 event_handler, 358 self, 359 &def_vector); 360 if (res != OK) { 361 // Something went wrong with transformation! 362 return res; 363 } 364 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg); 365 } 366 367 jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env, 368 art::Runtime* runtime, 369 art::Thread* self, 370 const std::vector<ArtClassDefinition>& definitions, 371 std::string* error_msg) { 372 DCHECK(env != nullptr); 373 if (definitions.size() == 0) { 374 // We don't actually need to do anything. Just return OK. 375 return OK; 376 } 377 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we 378 // are going to redefine. 379 art::jit::ScopedJitSuspend suspend_jit; 380 // Get shared mutator lock so we can lock all the classes. 381 art::ScopedObjectAccess soa(self); 382 Redefiner r(runtime, self, error_msg); 383 for (const ArtClassDefinition& def : definitions) { 384 // Only try to transform classes that have been modified. 385 if (def.IsModified()) { 386 jvmtiError res = r.AddRedefinition(env, def); 387 if (res != OK) { 388 return res; 389 } 390 } 391 } 392 return r.Run(); 393 } 394 395 jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) { 396 std::string original_dex_location; 397 jvmtiError ret = OK; 398 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) { 399 *error_msg_ = "Unable to get original dex file location!"; 400 return ret; 401 } 402 char* generic_ptr_unused = nullptr; 403 char* signature_ptr = nullptr; 404 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) { 405 *error_msg_ = "Unable to get class signature!"; 406 return ret; 407 } 408 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused)); 409 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr)); 410 std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location, 411 def.GetDexData(), 412 error_msg_)); 413 std::ostringstream os; 414 if (map.get() == nullptr) { 415 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName() 416 << "in dex file " << original_dex_location << " because: " << *error_msg_; 417 *error_msg_ = os.str(); 418 return ERR(OUT_OF_MEMORY); 419 } 420 if (map->Size() < sizeof(art::DexFile::Header)) { 421 *error_msg_ = "Could not read dex file header because dex_data was too short"; 422 return ERR(INVALID_CLASS_FORMAT); 423 } 424 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map->Begin())->checksum_; 425 std::unique_ptr<const art::DexFile> dex_file(art::DexFile::Open(map->GetName(), 426 checksum, 427 std::move(map), 428 /*verify*/true, 429 /*verify_checksum*/true, 430 error_msg_)); 431 if (dex_file.get() == nullptr) { 432 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_; 433 *error_msg_ = os.str(); 434 return ERR(INVALID_CLASS_FORMAT); 435 } 436 redefinitions_.push_back( 437 Redefiner::ClassRedefinition(this, 438 def.GetClass(), 439 dex_file.release(), 440 signature_ptr, 441 def.GetNewOriginalDexFile())); 442 return OK; 443 } 444 445 art::mirror::Class* Redefiner::ClassRedefinition::GetMirrorClass() { 446 return driver_->self_->DecodeJObject(klass_)->AsClass(); 447 } 448 449 art::mirror::ClassLoader* Redefiner::ClassRedefinition::GetClassLoader() { 450 return GetMirrorClass()->GetClassLoader(); 451 } 452 453 art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache( 454 art::Handle<art::mirror::ClassLoader> loader) { 455 return driver_->runtime_->GetClassLinker()->RegisterDexFile(*dex_file_, loader.Get()).Ptr(); 456 } 457 458 void Redefiner::RecordFailure(jvmtiError result, 459 const std::string& class_sig, 460 const std::string& error_msg) { 461 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s", 462 class_sig.c_str(), 463 error_msg.c_str()); 464 result_ = result; 465 } 466 467 art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() { 468 // If we have been specifically given a new set of bytes use that 469 if (original_dex_file_.size() != 0) { 470 return art::mirror::ByteArray::AllocateAndFill( 471 driver_->self_, 472 reinterpret_cast<const signed char*>(&original_dex_file_.At(0)), 473 original_dex_file_.size()); 474 } 475 476 // See if we already have one set. 477 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData()); 478 if (!ext.IsNull()) { 479 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile()); 480 if (!old_original_dex_file.IsNull()) { 481 // We do. Use it. 482 return old_original_dex_file.Ptr(); 483 } 484 } 485 486 // return the current dex_cache which has the dex file in it. 487 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache()); 488 // TODO Handle this or make it so it cannot happen. 489 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) { 490 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses " 491 << "on this class might fail if no transformations are applied to it!"; 492 } 493 return current_dex_cache.Ptr(); 494 } 495 496 struct CallbackCtx { 497 ObsoleteMap* obsolete_map; 498 art::LinearAlloc* allocator; 499 std::unordered_set<art::ArtMethod*> obsolete_methods; 500 501 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc) 502 : obsolete_map(map), allocator(alloc) {} 503 }; 504 505 void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS { 506 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata); 507 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t, 508 data->allocator, 509 data->obsolete_methods, 510 data->obsolete_map); 511 } 512 513 // This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is 514 // updated so they will be run. 515 // TODO Rewrite so we can do this only once regardless of how many redefinitions there are. 516 void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(art::mirror::Class* art_klass) { 517 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking"); 518 art::mirror::ClassExt* ext = art_klass->GetExtData(); 519 CHECK(ext->GetObsoleteMethods() != nullptr); 520 art::ClassLinker* linker = driver_->runtime_->GetClassLinker(); 521 // This holds pointers to the obsolete methods map fields which are updated as needed. 522 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache()); 523 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader())); 524 // Add all the declared methods to the map 525 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) { 526 if (m.IsIntrinsic()) { 527 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the " 528 << "unexpected use of the original definition of " << m.PrettyMethod() << "in " 529 << "methods that have already been compiled."; 530 } 531 // It is possible to simply filter out some methods where they cannot really become obsolete, 532 // such as native methods and keep their original (possibly optimized) implementations. We don't 533 // do this, however, since we would need to mark these functions (still in the classes 534 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data 535 // from (for example about stack-frame size). Furthermore we would be unable to get some useful 536 // error checking from the interpreter which ensure we don't try to start executing obsolete 537 // methods. 538 ctx.obsolete_methods.insert(&m); 539 } 540 { 541 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_); 542 art::ThreadList* list = art::Runtime::Current()->GetThreadList(); 543 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx)); 544 } 545 } 546 547 // Try and get the declared method. First try to get a virtual method then a direct method if that's 548 // not found. 549 static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass, 550 const char* name, 551 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) { 552 art::ArtMethod* m = klass->FindDeclaredVirtualMethod(name, sig, art::kRuntimePointerSize); 553 if (m == nullptr) { 554 m = klass->FindDeclaredDirectMethod(name, sig, art::kRuntimePointerSize); 555 } 556 return m; 557 } 558 559 bool Redefiner::ClassRedefinition::CheckSameMethods() { 560 art::StackHandleScope<1> hs(driver_->self_); 561 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass())); 562 DCHECK_EQ(dex_file_->NumClassDefs(), 1u); 563 564 art::ClassDataItemIterator new_iter(*dex_file_, 565 dex_file_->GetClassData(dex_file_->GetClassDef(0))); 566 567 // Make sure we have the same number of methods. 568 uint32_t num_new_method = new_iter.NumVirtualMethods() + new_iter.NumDirectMethods(); 569 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size(); 570 if (num_new_method != num_old_method) { 571 bool bigger = num_new_method > num_old_method; 572 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED) 573 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED), 574 StringPrintf("Total number of declared methods changed from %d to %d", 575 num_old_method, num_new_method)); 576 return false; 577 } 578 579 // Skip all of the fields. We should have already checked this. 580 while (new_iter.HasNextStaticField() || new_iter.HasNextInstanceField()) { 581 new_iter.Next(); 582 } 583 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex 584 // files have the same number of methods, which means there must be an equal amount of additions 585 // and removals. 586 for (; new_iter.HasNextVirtualMethod() || new_iter.HasNextDirectMethod(); new_iter.Next()) { 587 // Get the data on the method we are searching for 588 const art::DexFile::MethodId& new_method_id = dex_file_->GetMethodId(new_iter.GetMemberIndex()); 589 const char* new_method_name = dex_file_->GetMethodName(new_method_id); 590 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id); 591 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature); 592 // If we got past the check for the same number of methods above that means there must be at 593 // least one added and one removed method. We will return the ADDED failure message since it is 594 // easier to get a useful error report for it. 595 if (old_method == nullptr) { 596 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED), 597 StringPrintf("Unknown method '%s' (sig: %s) was added!", 598 new_method_name, 599 new_method_signature.ToString().c_str())); 600 return false; 601 } 602 // Since direct methods have different flags than virtual ones (specifically direct methods must 603 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from 604 // virtual to direct. 605 uint32_t new_flags = new_iter.GetMethodAccessFlags(); 606 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) { 607 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED), 608 StringPrintf("method '%s' (sig: %s) had different access flags", 609 new_method_name, 610 new_method_signature.ToString().c_str())); 611 return false; 612 } 613 } 614 return true; 615 } 616 617 bool Redefiner::ClassRedefinition::CheckSameFields() { 618 art::StackHandleScope<1> hs(driver_->self_); 619 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass())); 620 DCHECK_EQ(dex_file_->NumClassDefs(), 1u); 621 art::ClassDataItemIterator new_iter(*dex_file_, 622 dex_file_->GetClassData(dex_file_->GetClassDef(0))); 623 const art::DexFile& old_dex_file = h_klass->GetDexFile(); 624 art::ClassDataItemIterator old_iter(old_dex_file, 625 old_dex_file.GetClassData(*h_klass->GetClassDef())); 626 // Instance and static fields can be differentiated by their flags so no need to check them 627 // separately. 628 while (new_iter.HasNextInstanceField() || new_iter.HasNextStaticField()) { 629 // Get the data on the method we are searching for 630 const art::DexFile::FieldId& new_field_id = dex_file_->GetFieldId(new_iter.GetMemberIndex()); 631 const char* new_field_name = dex_file_->GetFieldName(new_field_id); 632 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id); 633 634 if (!(old_iter.HasNextInstanceField() || old_iter.HasNextStaticField())) { 635 // We are missing the old version of this method! 636 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED), 637 StringPrintf("Unknown field '%s' (type: %s) added!", 638 new_field_name, 639 new_field_type)); 640 return false; 641 } 642 643 const art::DexFile::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter.GetMemberIndex()); 644 const char* old_field_name = old_dex_file.GetFieldName(old_field_id); 645 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id); 646 647 // Check name and type. 648 if (strcmp(old_field_name, new_field_name) != 0 || 649 strcmp(old_field_type, new_field_type) != 0) { 650 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED), 651 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!", 652 old_field_name, 653 old_field_type, 654 new_field_name, 655 new_field_type)); 656 return false; 657 } 658 659 // Since static fields have different flags than instance ones (specifically static fields must 660 // have the kAccStatic flag) we can tell if a field changes from static to instance. 661 if (new_iter.GetFieldAccessFlags() != old_iter.GetFieldAccessFlags()) { 662 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED), 663 StringPrintf("Field '%s' (sig: %s) had different access flags", 664 new_field_name, 665 new_field_type)); 666 return false; 667 } 668 669 new_iter.Next(); 670 old_iter.Next(); 671 } 672 if (old_iter.HasNextInstanceField() || old_iter.HasNextStaticField()) { 673 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED), 674 StringPrintf("field '%s' (sig: %s) is missing!", 675 old_dex_file.GetFieldName(old_dex_file.GetFieldId( 676 old_iter.GetMemberIndex())), 677 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId( 678 old_iter.GetMemberIndex())))); 679 return false; 680 } 681 return true; 682 } 683 684 bool Redefiner::ClassRedefinition::CheckClass() { 685 art::StackHandleScope<1> hs(driver_->self_); 686 // Easy check that only 1 class def is present. 687 if (dex_file_->NumClassDefs() != 1) { 688 RecordFailure(ERR(ILLEGAL_ARGUMENT), 689 StringPrintf("Expected 1 class def in dex file but found %d", 690 dex_file_->NumClassDefs())); 691 return false; 692 } 693 // Get the ClassDef from the new DexFile. 694 // Since the dex file has only a single class def the index is always 0. 695 const art::DexFile::ClassDef& def = dex_file_->GetClassDef(0); 696 // Get the class as it is now. 697 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass())); 698 699 // Check the access flags didn't change. 700 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) { 701 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED), 702 "Cannot change modifiers of class by redefinition"); 703 return false; 704 } 705 706 // Check class name. 707 // These should have been checked by the dexfile verifier on load. 708 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index"; 709 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_); 710 DCHECK(descriptor != nullptr) << "Invalid dex file structure!"; 711 if (!current_class->DescriptorEquals(descriptor)) { 712 std::string storage; 713 RecordFailure(ERR(NAMES_DONT_MATCH), 714 StringPrintf("expected file to contain class called '%s' but found '%s'!", 715 current_class->GetDescriptor(&storage), 716 descriptor)); 717 return false; 718 } 719 if (current_class->IsObjectClass()) { 720 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) { 721 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!"); 722 return false; 723 } 724 } else { 725 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_); 726 DCHECK(descriptor != nullptr) << "Invalid dex file structure!"; 727 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) { 728 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed"); 729 return false; 730 } 731 } 732 const art::DexFile::TypeList* interfaces = dex_file_->GetInterfacesList(def); 733 if (interfaces == nullptr) { 734 if (current_class->NumDirectInterfaces() != 0) { 735 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added"); 736 return false; 737 } 738 } else { 739 DCHECK(!current_class->IsProxyClass()); 740 const art::DexFile::TypeList* current_interfaces = current_class->GetInterfaceTypeList(); 741 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) { 742 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed"); 743 return false; 744 } 745 // The order of interfaces is (barely) meaningful so we error if it changes. 746 const art::DexFile& orig_dex_file = current_class->GetDexFile(); 747 for (uint32_t i = 0; i < interfaces->Size(); i++) { 748 if (strcmp( 749 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_), 750 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) { 751 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), 752 "Interfaces changed or re-ordered"); 753 return false; 754 } 755 } 756 } 757 return true; 758 } 759 760 bool Redefiner::ClassRedefinition::CheckRedefinable() { 761 std::string err; 762 art::StackHandleScope<1> hs(driver_->self_); 763 764 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass())); 765 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err); 766 if (res != OK) { 767 RecordFailure(res, err); 768 return false; 769 } else { 770 return true; 771 } 772 } 773 774 bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() { 775 return CheckRedefinable() && 776 CheckClass() && 777 CheckSameFields() && 778 CheckSameMethods(); 779 } 780 781 class RedefinitionDataIter; 782 783 // A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a 784 // reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid 785 // having to deal with the fact that we need to hold an arbitrary number of references live. 786 class RedefinitionDataHolder { 787 public: 788 enum DataSlot : int32_t { 789 kSlotSourceClassLoader = 0, 790 kSlotJavaDexFile = 1, 791 kSlotNewDexFileCookie = 2, 792 kSlotNewDexCache = 3, 793 kSlotMirrorClass = 4, 794 kSlotOrigDexFile = 5, 795 kSlotOldObsoleteMethods = 6, 796 kSlotOldDexCaches = 7, 797 798 // Must be last one. 799 kNumSlots = 8, 800 }; 801 802 // This needs to have a HandleScope passed in that is capable of creating a new Handle without 803 // overflowing. Only one handle will be created. This object has a lifetime identical to that of 804 // the passed in handle-scope. 805 RedefinitionDataHolder(art::StackHandleScope<1>* hs, 806 art::Runtime* runtime, 807 art::Thread* self, 808 std::vector<Redefiner::ClassRedefinition>* redefinitions) 809 REQUIRES_SHARED(art::Locks::mutator_lock_) : 810 arr_( 811 hs->NewHandle( 812 art::mirror::ObjectArray<art::mirror::Object>::Alloc( 813 self, 814 runtime->GetClassLinker()->GetClassRoot(art::ClassLinker::kObjectArrayClass), 815 redefinitions->size() * kNumSlots))), 816 redefinitions_(redefinitions) {} 817 818 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) { 819 return arr_.IsNull(); 820 } 821 822 art::mirror::ClassLoader* GetSourceClassLoader(jint klass_index) const 823 REQUIRES_SHARED(art::Locks::mutator_lock_) { 824 return art::down_cast<art::mirror::ClassLoader*>(GetSlot(klass_index, kSlotSourceClassLoader)); 825 } 826 art::mirror::Object* GetJavaDexFile(jint klass_index) const 827 REQUIRES_SHARED(art::Locks::mutator_lock_) { 828 return GetSlot(klass_index, kSlotJavaDexFile); 829 } 830 art::mirror::LongArray* GetNewDexFileCookie(jint klass_index) const 831 REQUIRES_SHARED(art::Locks::mutator_lock_) { 832 return art::down_cast<art::mirror::LongArray*>(GetSlot(klass_index, kSlotNewDexFileCookie)); 833 } 834 art::mirror::DexCache* GetNewDexCache(jint klass_index) const 835 REQUIRES_SHARED(art::Locks::mutator_lock_) { 836 return art::down_cast<art::mirror::DexCache*>(GetSlot(klass_index, kSlotNewDexCache)); 837 } 838 art::mirror::Class* GetMirrorClass(jint klass_index) const 839 REQUIRES_SHARED(art::Locks::mutator_lock_) { 840 return art::down_cast<art::mirror::Class*>(GetSlot(klass_index, kSlotMirrorClass)); 841 } 842 843 art::mirror::Object* GetOriginalDexFile(jint klass_index) const 844 REQUIRES_SHARED(art::Locks::mutator_lock_) { 845 return art::down_cast<art::mirror::Object*>(GetSlot(klass_index, kSlotOrigDexFile)); 846 } 847 848 art::mirror::PointerArray* GetOldObsoleteMethods(jint klass_index) const 849 REQUIRES_SHARED(art::Locks::mutator_lock_) { 850 return art::down_cast<art::mirror::PointerArray*>( 851 GetSlot(klass_index, kSlotOldObsoleteMethods)); 852 } 853 854 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches(jint klass_index) const 855 REQUIRES_SHARED(art::Locks::mutator_lock_) { 856 return art::down_cast<art::mirror::ObjectArray<art::mirror::DexCache>*>( 857 GetSlot(klass_index, kSlotOldDexCaches)); 858 } 859 860 void SetSourceClassLoader(jint klass_index, art::mirror::ClassLoader* loader) 861 REQUIRES_SHARED(art::Locks::mutator_lock_) { 862 SetSlot(klass_index, kSlotSourceClassLoader, loader); 863 } 864 void SetJavaDexFile(jint klass_index, art::mirror::Object* dexfile) 865 REQUIRES_SHARED(art::Locks::mutator_lock_) { 866 SetSlot(klass_index, kSlotJavaDexFile, dexfile); 867 } 868 void SetNewDexFileCookie(jint klass_index, art::mirror::LongArray* cookie) 869 REQUIRES_SHARED(art::Locks::mutator_lock_) { 870 SetSlot(klass_index, kSlotNewDexFileCookie, cookie); 871 } 872 void SetNewDexCache(jint klass_index, art::mirror::DexCache* cache) 873 REQUIRES_SHARED(art::Locks::mutator_lock_) { 874 SetSlot(klass_index, kSlotNewDexCache, cache); 875 } 876 void SetMirrorClass(jint klass_index, art::mirror::Class* klass) 877 REQUIRES_SHARED(art::Locks::mutator_lock_) { 878 SetSlot(klass_index, kSlotMirrorClass, klass); 879 } 880 void SetOriginalDexFile(jint klass_index, art::mirror::Object* bytes) 881 REQUIRES_SHARED(art::Locks::mutator_lock_) { 882 SetSlot(klass_index, kSlotOrigDexFile, bytes); 883 } 884 void SetOldObsoleteMethods(jint klass_index, art::mirror::PointerArray* methods) 885 REQUIRES_SHARED(art::Locks::mutator_lock_) { 886 SetSlot(klass_index, kSlotOldObsoleteMethods, methods); 887 } 888 void SetOldDexCaches(jint klass_index, art::mirror::ObjectArray<art::mirror::DexCache>* caches) 889 REQUIRES_SHARED(art::Locks::mutator_lock_) { 890 SetSlot(klass_index, kSlotOldDexCaches, caches); 891 } 892 893 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) { 894 return arr_->GetLength() / kNumSlots; 895 } 896 897 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions() 898 REQUIRES_SHARED(art::Locks::mutator_lock_) { 899 return redefinitions_; 900 } 901 902 bool operator==(const RedefinitionDataHolder& other) const 903 REQUIRES_SHARED(art::Locks::mutator_lock_) { 904 return arr_.Get() == other.arr_.Get(); 905 } 906 907 bool operator!=(const RedefinitionDataHolder& other) const 908 REQUIRES_SHARED(art::Locks::mutator_lock_) { 909 return !(*this == other); 910 } 911 912 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_); 913 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_); 914 915 private: 916 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_; 917 std::vector<Redefiner::ClassRedefinition>* redefinitions_; 918 919 art::mirror::Object* GetSlot(jint klass_index, 920 DataSlot slot) const REQUIRES_SHARED(art::Locks::mutator_lock_) { 921 DCHECK_LT(klass_index, Length()); 922 return arr_->Get((kNumSlots * klass_index) + slot); 923 } 924 925 void SetSlot(jint klass_index, 926 DataSlot slot, 927 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) { 928 DCHECK(!art::Runtime::Current()->IsActiveTransaction()); 929 DCHECK_LT(klass_index, Length()); 930 arr_->Set<false>((kNumSlots * klass_index) + slot, obj); 931 } 932 933 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder); 934 }; 935 936 class RedefinitionDataIter { 937 public: 938 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {} 939 940 RedefinitionDataIter(const RedefinitionDataIter&) = default; 941 RedefinitionDataIter(RedefinitionDataIter&&) = default; 942 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default; 943 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default; 944 945 bool operator==(const RedefinitionDataIter& other) const 946 REQUIRES_SHARED(art::Locks::mutator_lock_) { 947 return idx_ == other.idx_ && holder_ == other.holder_; 948 } 949 950 bool operator!=(const RedefinitionDataIter& other) const 951 REQUIRES_SHARED(art::Locks::mutator_lock_) { 952 return !(*this == other); 953 } 954 955 RedefinitionDataIter operator++() { // Value after modification. 956 idx_++; 957 return *this; 958 } 959 960 RedefinitionDataIter operator++(int) { 961 RedefinitionDataIter temp = *this; 962 idx_++; 963 return temp; 964 } 965 966 RedefinitionDataIter operator+(ssize_t delta) const { 967 RedefinitionDataIter temp = *this; 968 temp += delta; 969 return temp; 970 } 971 972 RedefinitionDataIter& operator+=(ssize_t delta) { 973 idx_ += delta; 974 return *this; 975 } 976 977 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) { 978 return (*holder_.GetRedefinitions())[idx_]; 979 } 980 981 RedefinitionDataHolder& GetHolder() { 982 return holder_; 983 } 984 985 art::mirror::ClassLoader* GetSourceClassLoader() const 986 REQUIRES_SHARED(art::Locks::mutator_lock_) { 987 return holder_.GetSourceClassLoader(idx_); 988 } 989 art::mirror::Object* GetJavaDexFile() const REQUIRES_SHARED(art::Locks::mutator_lock_) { 990 return holder_.GetJavaDexFile(idx_); 991 } 992 art::mirror::LongArray* GetNewDexFileCookie() const REQUIRES_SHARED(art::Locks::mutator_lock_) { 993 return holder_.GetNewDexFileCookie(idx_); 994 } 995 art::mirror::DexCache* GetNewDexCache() const REQUIRES_SHARED(art::Locks::mutator_lock_) { 996 return holder_.GetNewDexCache(idx_); 997 } 998 art::mirror::Class* GetMirrorClass() const REQUIRES_SHARED(art::Locks::mutator_lock_) { 999 return holder_.GetMirrorClass(idx_); 1000 } 1001 art::mirror::Object* GetOriginalDexFile() const 1002 REQUIRES_SHARED(art::Locks::mutator_lock_) { 1003 return holder_.GetOriginalDexFile(idx_); 1004 } 1005 art::mirror::PointerArray* GetOldObsoleteMethods() const 1006 REQUIRES_SHARED(art::Locks::mutator_lock_) { 1007 return holder_.GetOldObsoleteMethods(idx_); 1008 } 1009 art::mirror::ObjectArray<art::mirror::DexCache>* GetOldDexCaches() const 1010 REQUIRES_SHARED(art::Locks::mutator_lock_) { 1011 return holder_.GetOldDexCaches(idx_); 1012 } 1013 1014 int32_t GetIndex() const { 1015 return idx_; 1016 } 1017 1018 void SetSourceClassLoader(art::mirror::ClassLoader* loader) 1019 REQUIRES_SHARED(art::Locks::mutator_lock_) { 1020 holder_.SetSourceClassLoader(idx_, loader); 1021 } 1022 void SetJavaDexFile(art::mirror::Object* dexfile) REQUIRES_SHARED(art::Locks::mutator_lock_) { 1023 holder_.SetJavaDexFile(idx_, dexfile); 1024 } 1025 void SetNewDexFileCookie(art::mirror::LongArray* cookie) 1026 REQUIRES_SHARED(art::Locks::mutator_lock_) { 1027 holder_.SetNewDexFileCookie(idx_, cookie); 1028 } 1029 void SetNewDexCache(art::mirror::DexCache* cache) REQUIRES_SHARED(art::Locks::mutator_lock_) { 1030 holder_.SetNewDexCache(idx_, cache); 1031 } 1032 void SetMirrorClass(art::mirror::Class* klass) REQUIRES_SHARED(art::Locks::mutator_lock_) { 1033 holder_.SetMirrorClass(idx_, klass); 1034 } 1035 void SetOriginalDexFile(art::mirror::Object* bytes) 1036 REQUIRES_SHARED(art::Locks::mutator_lock_) { 1037 holder_.SetOriginalDexFile(idx_, bytes); 1038 } 1039 void SetOldObsoleteMethods(art::mirror::PointerArray* methods) 1040 REQUIRES_SHARED(art::Locks::mutator_lock_) { 1041 holder_.SetOldObsoleteMethods(idx_, methods); 1042 } 1043 void SetOldDexCaches(art::mirror::ObjectArray<art::mirror::DexCache>* caches) 1044 REQUIRES_SHARED(art::Locks::mutator_lock_) { 1045 holder_.SetOldDexCaches(idx_, caches); 1046 } 1047 1048 private: 1049 int32_t idx_; 1050 RedefinitionDataHolder& holder_; 1051 }; 1052 1053 RedefinitionDataIter RedefinitionDataHolder::begin() { 1054 return RedefinitionDataIter(0, *this); 1055 } 1056 1057 RedefinitionDataIter RedefinitionDataHolder::end() { 1058 return RedefinitionDataIter(Length(), *this); 1059 } 1060 1061 bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) { 1062 DCHECK_EQ(dex_file_->NumClassDefs(), 1u); 1063 art::StackHandleScope<2> hs(driver_->self_); 1064 std::string error; 1065 // TODO Make verification log level lower 1066 art::verifier::FailureKind failure = 1067 art::verifier::MethodVerifier::VerifyClass(driver_->self_, 1068 dex_file_.get(), 1069 hs.NewHandle(iter.GetNewDexCache()), 1070 hs.NewHandle(GetClassLoader()), 1071 dex_file_->GetClassDef(0), /*class_def*/ 1072 nullptr, /*compiler_callbacks*/ 1073 false, /*allow_soft_failures*/ 1074 /*log_level*/ 1075 art::verifier::HardFailLogMode::kLogWarning, 1076 &error); 1077 bool passes = failure == art::verifier::FailureKind::kNoFailure; 1078 if (!passes) { 1079 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error); 1080 } 1081 return passes; 1082 } 1083 1084 // Looks through the previously allocated cookies to see if we need to update them with another new 1085 // dexfile. This is so that even if multiple classes with the same classloader are redefined at 1086 // once they are all added to the classloader. 1087 bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie( 1088 art::Handle<art::mirror::ClassLoader> source_class_loader, 1089 art::Handle<art::mirror::Object> dex_file_obj, 1090 /*out*/RedefinitionDataIter* cur_data) { 1091 art::StackHandleScope<2> hs(driver_->self_); 1092 art::MutableHandle<art::mirror::LongArray> old_cookie( 1093 hs.NewHandle<art::mirror::LongArray>(nullptr)); 1094 bool has_older_cookie = false; 1095 // See if we already have a cookie that a previous redefinition got from the same classloader. 1096 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) { 1097 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) { 1098 // Since every instance of this classloader should have the same cookie associated with it we 1099 // can stop looking here. 1100 has_older_cookie = true; 1101 old_cookie.Assign(old_data.GetNewDexFileCookie()); 1102 break; 1103 } 1104 } 1105 if (old_cookie.IsNull()) { 1106 // No older cookie. Get it directly from the dex_file_obj 1107 // We should not have seen this classloader elsewhere. 1108 CHECK(!has_older_cookie); 1109 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj)); 1110 } 1111 // Use the old cookie to generate the new one with the new DexFile* added in. 1112 art::Handle<art::mirror::LongArray> 1113 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_, 1114 old_cookie, 1115 dex_file_.get()))); 1116 // Make sure the allocation worked. 1117 if (new_cookie.IsNull()) { 1118 return false; 1119 } 1120 1121 // Save the cookie. 1122 cur_data->SetNewDexFileCookie(new_cookie.Get()); 1123 // If there are other copies of this same classloader we need to make sure that we all have the 1124 // same cookie. 1125 if (has_older_cookie) { 1126 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) { 1127 // We will let the GC take care of the cookie we allocated for this one. 1128 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) { 1129 old_data.SetNewDexFileCookie(new_cookie.Get()); 1130 } 1131 } 1132 } 1133 1134 return true; 1135 } 1136 1137 bool Redefiner::ClassRedefinition::FinishRemainingAllocations( 1138 /*out*/RedefinitionDataIter* cur_data) { 1139 art::ScopedObjectAccessUnchecked soa(driver_->self_); 1140 art::StackHandleScope<2> hs(driver_->self_); 1141 cur_data->SetMirrorClass(GetMirrorClass()); 1142 // This shouldn't allocate 1143 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader())); 1144 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile. 1145 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) { 1146 cur_data->SetSourceClassLoader(loader.Get()); 1147 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle( 1148 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader))); 1149 cur_data->SetJavaDexFile(dex_file_obj.Get()); 1150 if (dex_file_obj == nullptr) { 1151 RecordFailure(ERR(INTERNAL), "Unable to find dex file!"); 1152 return false; 1153 } 1154 // Allocate the new dex file cookie. 1155 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) { 1156 driver_->self_->AssertPendingOOMException(); 1157 driver_->self_->ClearException(); 1158 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader"); 1159 return false; 1160 } 1161 } 1162 cur_data->SetNewDexCache(CreateNewDexCache(loader)); 1163 if (cur_data->GetNewDexCache() == nullptr) { 1164 driver_->self_->AssertPendingException(); 1165 driver_->self_->ClearException(); 1166 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache"); 1167 return false; 1168 } 1169 1170 // We won't always need to set this field. 1171 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile()); 1172 if (cur_data->GetOriginalDexFile() == nullptr) { 1173 driver_->self_->AssertPendingOOMException(); 1174 driver_->self_->ClearException(); 1175 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file"); 1176 return false; 1177 } 1178 return true; 1179 } 1180 1181 void Redefiner::ClassRedefinition::UnregisterBreakpoints() { 1182 DCHECK(art::Dbg::IsDebuggerActive()); 1183 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState(); 1184 if (state != nullptr) { 1185 state->UnregisterLocationEventsOnClass(GetMirrorClass()); 1186 } 1187 } 1188 1189 void Redefiner::UnregisterAllBreakpoints() { 1190 if (LIKELY(!art::Dbg::IsDebuggerActive())) { 1191 return; 1192 } 1193 for (Redefiner::ClassRedefinition& redef : redefinitions_) { 1194 redef.UnregisterBreakpoints(); 1195 } 1196 } 1197 1198 bool Redefiner::CheckAllRedefinitionAreValid() { 1199 for (Redefiner::ClassRedefinition& redef : redefinitions_) { 1200 if (!redef.CheckRedefinitionIsValid()) { 1201 return false; 1202 } 1203 } 1204 return true; 1205 } 1206 1207 void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) { 1208 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) { 1209 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data); 1210 } 1211 } 1212 1213 bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) { 1214 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) { 1215 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) { 1216 return false; 1217 } 1218 } 1219 return true; 1220 } 1221 1222 bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) { 1223 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) { 1224 // Allocate the data this redefinition requires. 1225 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) { 1226 return false; 1227 } 1228 } 1229 return true; 1230 } 1231 1232 void Redefiner::ClassRedefinition::ReleaseDexFile() { 1233 dex_file_.release(); 1234 } 1235 1236 void Redefiner::ReleaseAllDexFiles() { 1237 for (Redefiner::ClassRedefinition& redef : redefinitions_) { 1238 redef.ReleaseDexFile(); 1239 } 1240 } 1241 1242 bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) { 1243 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) { 1244 if (!data.GetRedefinition().CheckVerification(data)) { 1245 return false; 1246 } 1247 } 1248 return true; 1249 } 1250 1251 class ScopedDisableConcurrentAndMovingGc { 1252 public: 1253 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self) 1254 : heap_(heap), self_(self) { 1255 if (heap_->IsGcConcurrentAndMoving()) { 1256 heap_->IncrementDisableMovingGC(self_); 1257 } 1258 } 1259 1260 ~ScopedDisableConcurrentAndMovingGc() { 1261 if (heap_->IsGcConcurrentAndMoving()) { 1262 heap_->DecrementDisableMovingGC(self_); 1263 } 1264 } 1265 private: 1266 art::gc::Heap* heap_; 1267 art::Thread* self_; 1268 }; 1269 1270 jvmtiError Redefiner::Run() { 1271 art::StackHandleScope<1> hs(self_); 1272 // Allocate an array to hold onto all java temporary objects associated with this redefinition. 1273 // We will let this be collected after the end of this function. 1274 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_); 1275 if (holder.IsNull()) { 1276 self_->AssertPendingOOMException(); 1277 self_->ClearException(); 1278 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries"); 1279 return result_; 1280 } 1281 1282 // First we just allocate the ClassExt and its fields that we need. These can be updated 1283 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother 1284 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time 1285 // between allocating them and pausing all threads before we can update them so we need to do a 1286 // try loop. 1287 if (!CheckAllRedefinitionAreValid() || 1288 !EnsureAllClassAllocationsFinished(holder) || 1289 !FinishAllRemainingAllocations(holder) || 1290 !CheckAllClassesAreVerified(holder)) { 1291 return result_; 1292 } 1293 1294 // At this point we can no longer fail without corrupting the runtime state. 1295 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) { 1296 if (data.GetSourceClassLoader() == nullptr) { 1297 runtime_->GetClassLinker()->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile()); 1298 } 1299 } 1300 UnregisterAllBreakpoints(); 1301 1302 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done 1303 // allocating so no deadlocks. 1304 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_); 1305 1306 // Do transition to final suspension 1307 // TODO We might want to give this its own suspended state! 1308 // TODO This isn't right. We need to change state without any chance of suspend ideally! 1309 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative); 1310 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend*/true); 1311 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) { 1312 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition"); 1313 ClassRedefinition& redef = data.GetRedefinition(); 1314 if (data.GetSourceClassLoader() != nullptr) { 1315 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie()); 1316 } 1317 art::mirror::Class* klass = data.GetMirrorClass(); 1318 // TODO Rewrite so we don't do a stack walk for each and every class. 1319 redef.FindAndAllocateObsoleteMethods(klass); 1320 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile()); 1321 } 1322 RestoreObsoleteMethodMapsIfUnneeded(holder); 1323 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any 1324 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then 1325 // methods that have been jitted prior to the current redefinition being applied might continue 1326 // to use the old versions of the intrinsics! 1327 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really 1328 // owns the DexFile and when ownership is transferred. 1329 ReleaseAllDexFiles(); 1330 return OK; 1331 } 1332 1333 void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass, 1334 art::ObjPtr<art::mirror::DexCache> new_dex_cache, 1335 const art::DexFile::ClassDef& class_def) { 1336 art::ClassLinker* linker = driver_->runtime_->GetClassLinker(); 1337 art::PointerSize image_pointer_size = linker->GetImagePointerSize(); 1338 const art::DexFile::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_); 1339 const art::DexFile& old_dex_file = mclass->GetDexFile(); 1340 // Update methods. 1341 for (art::ArtMethod& method : mclass->GetMethods(image_pointer_size)) { 1342 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(method.GetName()); 1343 art::dex::TypeIndex method_return_idx = 1344 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor())); 1345 const auto* old_type_list = method.GetParameterTypeList(); 1346 std::vector<art::dex::TypeIndex> new_type_list; 1347 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) { 1348 new_type_list.push_back( 1349 dex_file_->GetIndexForTypeId( 1350 *dex_file_->FindTypeId( 1351 old_dex_file.GetTypeDescriptor( 1352 old_dex_file.GetTypeId( 1353 old_type_list->GetTypeItem(i).type_idx_))))); 1354 } 1355 const art::DexFile::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx, 1356 new_type_list); 1357 CHECK(proto_id != nullptr || old_type_list == nullptr); 1358 const art::DexFile::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id, 1359 *new_name_id, 1360 *proto_id); 1361 CHECK(method_id != nullptr); 1362 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id); 1363 method.SetDexMethodIndex(dex_method_idx); 1364 linker->SetEntryPointsToInterpreter(&method); 1365 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx)); 1366 method.SetDexCacheResolvedMethods(new_dex_cache->GetResolvedMethods(), image_pointer_size); 1367 // Clear all the intrinsics related flags. 1368 method.ClearAccessFlags(art::kAccIntrinsic | (~art::kAccFlagsNotUsedByIntrinsic)); 1369 // Notify the jit that this method is redefined. 1370 art::jit::Jit* jit = driver_->runtime_->GetJit(); 1371 if (jit != nullptr) { 1372 jit->GetCodeCache()->NotifyMethodRedefined(&method); 1373 } 1374 } 1375 } 1376 1377 void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) { 1378 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were. 1379 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) { 1380 for (art::ArtField& field : fields_iter) { 1381 std::string declaring_class_name; 1382 const art::DexFile::TypeId* new_declaring_id = 1383 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name)); 1384 const art::DexFile::StringId* new_name_id = dex_file_->FindStringId(field.GetName()); 1385 const art::DexFile::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor()); 1386 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr); 1387 const art::DexFile::FieldId* new_field_id = 1388 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id); 1389 CHECK(new_field_id != nullptr); 1390 // We only need to update the index since the other data in the ArtField cannot be updated. 1391 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id)); 1392 } 1393 } 1394 } 1395 1396 // Performs updates to class that will allow us to verify it. 1397 void Redefiner::ClassRedefinition::UpdateClass( 1398 art::ObjPtr<art::mirror::Class> mclass, 1399 art::ObjPtr<art::mirror::DexCache> new_dex_cache, 1400 art::ObjPtr<art::mirror::Object> original_dex_file) { 1401 DCHECK_EQ(dex_file_->NumClassDefs(), 1u); 1402 const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0); 1403 UpdateMethods(mclass, new_dex_cache, class_def); 1404 UpdateFields(mclass); 1405 1406 // Update the class fields. 1407 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed 1408 // to call GetReturnTypeDescriptor and GetParameterTypeList above). 1409 mclass->SetDexCache(new_dex_cache.Ptr()); 1410 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def)); 1411 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str()))); 1412 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData()); 1413 CHECK(!ext.IsNull()); 1414 ext->SetOriginalDexFile(original_dex_file); 1415 } 1416 1417 // Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new 1418 // obsolete methods). 1419 void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded( 1420 const RedefinitionDataIter* cur_data) { 1421 art::mirror::Class* klass = GetMirrorClass(); 1422 art::mirror::ClassExt* ext = klass->GetExtData(); 1423 art::mirror::PointerArray* methods = ext->GetObsoleteMethods(); 1424 art::mirror::PointerArray* old_methods = cur_data->GetOldObsoleteMethods(); 1425 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength(); 1426 int32_t expected_length = 1427 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods(); 1428 // Check to make sure we are only undoing this one. 1429 if (expected_length == methods->GetLength()) { 1430 for (int32_t i = 0; i < expected_length; i++) { 1431 art::ArtMethod* expected = nullptr; 1432 if (i < old_length) { 1433 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize); 1434 } 1435 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) { 1436 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the 1437 // obsolete methods array. 1438 return; 1439 } 1440 } 1441 // No new obsolete methods! We can get rid of the maps. 1442 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches()); 1443 } 1444 } 1445 1446 // This function does all (java) allocations we need to do for the Class being redefined. 1447 // TODO Change this name maybe? 1448 bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished( 1449 /*out*/RedefinitionDataIter* cur_data) { 1450 art::StackHandleScope<2> hs(driver_->self_); 1451 art::Handle<art::mirror::Class> klass(hs.NewHandle( 1452 driver_->self_->DecodeJObject(klass_)->AsClass())); 1453 if (klass == nullptr) { 1454 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!"); 1455 return false; 1456 } 1457 // Allocate the classExt 1458 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_))); 1459 if (ext == nullptr) { 1460 // No memory. Clear exception (it's not useful) and return error. 1461 driver_->self_->AssertPendingOOMException(); 1462 driver_->self_->ClearException(); 1463 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt"); 1464 return false; 1465 } 1466 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then 1467 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays 1468 // are only modified when all threads (other than the modifying one) are suspended we don't need 1469 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it 1470 // however, since that can happen at any time. 1471 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods()); 1472 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches()); 1473 if (!ext->ExtendObsoleteArrays( 1474 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) { 1475 // OOM. Clear exception and return error. 1476 driver_->self_->AssertPendingOOMException(); 1477 driver_->self_->ClearException(); 1478 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map"); 1479 return false; 1480 } 1481 return true; 1482 } 1483 1484 } // namespace openjdkjvmti 1485