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 <algorithm>
35 #include <atomic>
36 #include <iterator>
37 #include <limits>
38 #include <sstream>
39 #include <string_view>
40 #include <unordered_map>
41 
42 #include <android-base/logging.h>
43 #include <android-base/stringprintf.h>
44 
45 #include "alloc_manager.h"
46 #include "android-base/macros.h"
47 #include "android-base/thread_annotations.h"
48 #include "art_field-inl.h"
49 #include "art_field.h"
50 #include "art_jvmti.h"
51 #include "art_method-inl.h"
52 #include "art_method.h"
53 #include "base/array_ref.h"
54 #include "base/casts.h"
55 #include "base/globals.h"
56 #include "base/iteration_range.h"
57 #include "base/length_prefixed_array.h"
58 #include "base/locks.h"
59 #include "base/pointer_size.h"
60 #include "base/stl_util.h"
61 #include "base/utils.h"
62 #include "class_linker-inl.h"
63 #include "class_linker.h"
64 #include "class_root-inl.h"
65 #include "class_status.h"
66 #include "debugger.h"
67 #include "dex/art_dex_file_loader.h"
68 #include "dex/class_accessor-inl.h"
69 #include "dex/class_accessor.h"
70 #include "dex/dex_file.h"
71 #include "dex/dex_file_loader.h"
72 #include "dex/dex_file_types.h"
73 #include "dex/primitive.h"
74 #include "dex/signature-inl.h"
75 #include "dex/signature.h"
76 #include "events-inl.h"
77 #include "events.h"
78 #include "gc/allocation_listener.h"
79 #include "gc/heap.h"
80 #include "gc/heap-inl.h"
81 #include "gc/heap-visit-objects-inl.h"
82 #include "handle.h"
83 #include "handle_scope.h"
84 #include "instrumentation.h"
85 #include "intern_table.h"
86 #include "jit/jit.h"
87 #include "jit/jit_code_cache.h"
88 #include "jni/jni_env_ext-inl.h"
89 #include "jni/jni_id_manager.h"
90 #include "jvmti.h"
91 #include "jvmti_allocator.h"
92 #include "linear_alloc-inl.h"
93 #include "mirror/array-alloc-inl.h"
94 #include "mirror/array.h"
95 #include "mirror/class-alloc-inl.h"
96 #include "mirror/class-inl.h"
97 #include "mirror/class-refvisitor-inl.h"
98 #include "mirror/class.h"
99 #include "mirror/class_ext-inl.h"
100 #include "mirror/dex_cache-inl.h"
101 #include "mirror/dex_cache.h"
102 #include "mirror/executable-inl.h"
103 #include "mirror/field-inl.h"
104 #include "mirror/field.h"
105 #include "mirror/method.h"
106 #include "mirror/method_handle_impl-inl.h"
107 #include "mirror/object.h"
108 #include "mirror/object_array-alloc-inl.h"
109 #include "mirror/object_array-inl.h"
110 #include "mirror/object_array.h"
111 #include "mirror/string.h"
112 #include "mirror/var_handle.h"
113 #include "nativehelper/scoped_local_ref.h"
114 #include "non_debuggable_classes.h"
115 #include "obj_ptr.h"
116 #include "object_lock.h"
117 #include "reflective_value_visitor.h"
118 #include "runtime.h"
119 #include "runtime_globals.h"
120 #include "scoped_thread_state_change.h"
121 #include "stack.h"
122 #include "thread.h"
123 #include "thread_list.h"
124 #include "ti_breakpoint.h"
125 #include "ti_class_definition.h"
126 #include "ti_class_loader.h"
127 #include "ti_heap.h"
128 #include "ti_logging.h"
129 #include "ti_thread.h"
130 #include "transform.h"
131 #include "verifier/class_verifier.h"
132 #include "verifier/verifier_enums.h"
133 #include "well_known_classes-inl.h"
134 #include "write_barrier.h"
135 
136 namespace openjdkjvmti {
137 
138 // Debug check to force us to directly check we saw all methods and fields exactly once directly.
139 // Normally we don't need to do this since if any are missing the count will be different
140 constexpr bool kCheckAllMethodsSeenOnce = art::kIsDebugBuild;
141 
142 using android::base::StringPrintf;
143 
144 // A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
145 // they are created. This ensures that we can always call any method of an obsolete ArtMethod object
146 // almost as soon as they are created since the GetObsoleteDexCache method will succeed.
147 class ObsoleteMap {
148  public:
FindObsoleteVersion(art::ArtMethod * original) const149   art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original) const
150       REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
151     auto method_pair = id_map_.find(original);
152     if (method_pair != id_map_.end()) {
153       art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
154           method_pair->second, art::kRuntimePointerSize);
155       DCHECK(res != nullptr);
156       return res;
157     } else {
158       return nullptr;
159     }
160   }
161 
RecordObsolete(art::ArtMethod * original,art::ArtMethod * obsolete)162   void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
163       REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
164     DCHECK(original != nullptr);
165     DCHECK(obsolete != nullptr);
166     int32_t slot = next_free_slot_++;
167     DCHECK_LT(slot, obsolete_methods_->GetLength());
168     DCHECK(nullptr ==
169            obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
170     DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
171     obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
172     obsolete_dex_caches_->Set(slot, original_dex_cache_);
173     id_map_.insert({original, slot});
174   }
175 
ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,art::ObjPtr<art::mirror::DexCache> original_dex_cache)176   ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
177               art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
178               art::ObjPtr<art::mirror::DexCache> original_dex_cache)
179       : next_free_slot_(0),
180         obsolete_methods_(obsolete_methods),
181         obsolete_dex_caches_(obsolete_dex_caches),
182         original_dex_cache_(original_dex_cache) {
183     // Figure out where the first unused slot in the obsolete_methods_ array is.
184     while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
185         next_free_slot_, art::kRuntimePointerSize) != nullptr) {
186       DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
187       next_free_slot_++;
188     }
189     // Check that the same slot in obsolete_dex_caches_ is free.
190     DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
191   }
192 
193   struct ObsoleteMethodPair {
194     art::ArtMethod* old_method;
195     art::ArtMethod* obsolete_method;
196   };
197 
198   class ObsoleteMapIter {
199    public:
200     using iterator_category = std::forward_iterator_tag;
201     using value_type = ObsoleteMethodPair;
202     using difference_type = ptrdiff_t;
203     using pointer = void;    // Unsupported.
204     using reference = void;  // Unsupported.
205 
operator *() const206     ObsoleteMethodPair operator*() const
207         REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
208       art::ArtMethod* obsolete = map_->obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
209           iter_->second, art::kRuntimePointerSize);
210       DCHECK(obsolete != nullptr);
211       return { iter_->first, obsolete };
212     }
213 
operator ==(ObsoleteMapIter other) const214     bool operator==(ObsoleteMapIter other) const {
215       return map_ == other.map_ && iter_ == other.iter_;
216     }
217 
operator !=(ObsoleteMapIter other) const218     bool operator!=(ObsoleteMapIter other) const {
219       return !(*this == other);
220     }
221 
operator ++(int)222     ObsoleteMapIter operator++(int) {
223       ObsoleteMapIter retval = *this;
224       ++(*this);
225       return retval;
226     }
227 
operator ++()228     ObsoleteMapIter operator++() {
229       ++iter_;
230       return *this;
231     }
232 
233    private:
ObsoleteMapIter(const ObsoleteMap * map,std::unordered_map<art::ArtMethod *,int32_t>::const_iterator iter)234     ObsoleteMapIter(const ObsoleteMap* map,
235                     std::unordered_map<art::ArtMethod*, int32_t>::const_iterator iter)
236         : map_(map), iter_(iter) {}
237 
238     const ObsoleteMap* map_;
239     std::unordered_map<art::ArtMethod*, int32_t>::const_iterator iter_;
240 
241     friend class ObsoleteMap;
242   };
243 
end() const244   ObsoleteMapIter end() const {
245     return ObsoleteMapIter(this, id_map_.cend());
246   }
247 
begin() const248   ObsoleteMapIter begin() const {
249     return ObsoleteMapIter(this, id_map_.cbegin());
250   }
251 
252  private:
253   int32_t next_free_slot_;
254   std::unordered_map<art::ArtMethod*, int32_t> id_map_;
255   // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
256   // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
257   art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
258   art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
259   art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
260 };
261 
262 // This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
263 // some basic soundness checks that the obsolete method is valid.
264 class ObsoleteMethodStackVisitor : public art::StackVisitor {
265  protected:
ObsoleteMethodStackVisitor(art::Thread * thread,art::LinearAlloc * allocator,const std::unordered_set<art::ArtMethod * > & obsoleted_methods,ObsoleteMap * obsolete_maps)266   ObsoleteMethodStackVisitor(
267       art::Thread* thread,
268       art::LinearAlloc* allocator,
269       const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
270       ObsoleteMap* obsolete_maps)
271         : StackVisitor(thread,
272                        /*context=*/nullptr,
273                        StackVisitor::StackWalkKind::kIncludeInlinedFrames),
274           allocator_(allocator),
275           obsoleted_methods_(obsoleted_methods),
276           obsolete_maps_(obsolete_maps) { }
277 
~ObsoleteMethodStackVisitor()278   ~ObsoleteMethodStackVisitor() override {}
279 
280  public:
281   // Returns true if we successfully installed obsolete methods on this thread, filling
282   // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
283   // The stack is cleaned up when we fail.
UpdateObsoleteFrames(art::Thread * thread,art::LinearAlloc * allocator,const std::unordered_set<art::ArtMethod * > & obsoleted_methods,ObsoleteMap * obsolete_maps)284   static void UpdateObsoleteFrames(
285       art::Thread* thread,
286       art::LinearAlloc* allocator,
287       const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
288       ObsoleteMap* obsolete_maps) REQUIRES(art::Locks::mutator_lock_) {
289     ObsoleteMethodStackVisitor visitor(thread,
290                                        allocator,
291                                        obsoleted_methods,
292                                        obsolete_maps);
293     visitor.WalkStack();
294   }
295 
VisitFrame()296   bool VisitFrame() override REQUIRES(art::Locks::mutator_lock_) {
297     art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
298     art::ArtMethod* old_method = GetMethod();
299     if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
300       // We cannot ensure that the right dex file is used in inlined frames so we don't support
301       // redefining them.
302       DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition: "
303                                   << old_method->PrettyMethod() << " is inlined into "
304                                   << GetOuterMethod()->PrettyMethod();
305       art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
306       if (new_obsolete_method == nullptr) {
307         // Create a new Obsolete Method and put it in the list.
308         art::Runtime* runtime = art::Runtime::Current();
309         art::ClassLinker* cl = runtime->GetClassLinker();
310         auto ptr_size = cl->GetImagePointerSize();
311         const size_t method_size = art::ArtMethod::Size(ptr_size);
312         auto* method_storage = allocator_->Alloc(art::Thread::Current(),
313                                                  method_size,
314                                                  art::LinearAllocKind::kArtMethod);
315         CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
316                                          << old_method->PrettyMethod() << "'";
317         new_obsolete_method = new (method_storage) art::ArtMethod();
318         new_obsolete_method->CopyFrom(old_method, ptr_size);
319         DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
320         new_obsolete_method->SetIsObsolete();
321         new_obsolete_method->SetDontCompile();
322         cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
323         obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
324       }
325       DCHECK(new_obsolete_method != nullptr);
326       SetMethod(new_obsolete_method);
327     }
328     return true;
329   }
330 
331  private:
332   // The linear allocator we should use to make new methods.
333   art::LinearAlloc* allocator_;
334   // The set of all methods which could be obsoleted.
335   const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
336   // A map from the original to the newly allocated obsolete method for frames on this thread. The
337   // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
338   // the redefined classes ClassExt as it is filled.
339   ObsoleteMap* obsolete_maps_;
340 };
341 
342 namespace {
343 // We need to make sure we only have one redefinition in progress. Redefining involves
344 // re-verification and potentially new allocations among other things. So we only allow one
345 // redefinition at a time.
346 static art::Mutex redefinition_lock("JVMTI Redefinition lock", art::LockLevel::kGenericBottomLock);
347 static bool redefinition_in_progress GUARDED_BY(redefinition_lock) = false;
348 
canHandleRedefinition(art::Thread * self)349 bool canHandleRedefinition(art::Thread* self) {
350   art::MutexLock mu(self, redefinition_lock);
351   if (redefinition_in_progress) {
352     return false;
353   }
354   redefinition_in_progress = true;
355   return true;
356 }
357 
finishRedefinition(art::Thread * self)358 void finishRedefinition(art::Thread* self) {
359   art::MutexLock mu(self, redefinition_lock);
360   DCHECK_EQ(redefinition_in_progress, true);
361   redefinition_in_progress = false;
362 }
363 }  // namespace
364 
365 template <RedefinitionType kType>
366 jvmtiError
IsModifiableClassGeneric(jvmtiEnv * env,jclass klass,jboolean * is_redefinable)367 Redefiner::IsModifiableClassGeneric(jvmtiEnv* env, jclass klass, jboolean* is_redefinable) {
368   if (env == nullptr) {
369     return ERR(INVALID_ENVIRONMENT);
370   }
371   art::Thread* self = art::Thread::Current();
372   art::ScopedObjectAccess soa(self);
373   art::StackHandleScope<1> hs(self);
374   art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
375   if (obj.IsNull() || !obj->IsClass()) {
376     return ERR(INVALID_CLASS);
377   }
378   art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
379   std::string err_unused;
380   *is_redefinable =
381       Redefiner::CanRedefineClass<kType>(h_klass, &err_unused) != ERR(UNMODIFIABLE_CLASS)
382           ? JNI_TRUE
383           : JNI_FALSE;
384   return OK;
385 }
386 
387 jvmtiError
IsStructurallyModifiableClass(jvmtiEnv * env,jclass klass,jboolean * is_redefinable)388 Redefiner::IsStructurallyModifiableClass(jvmtiEnv* env, jclass klass, jboolean* is_redefinable) {
389   return Redefiner::IsModifiableClassGeneric<RedefinitionType::kStructural>(
390       env, klass, is_redefinable);
391 }
392 
IsModifiableClass(jvmtiEnv * env,jclass klass,jboolean * is_redefinable)393 jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env, jclass klass, jboolean* is_redefinable) {
394   return Redefiner::IsModifiableClassGeneric<RedefinitionType::kNormal>(env, klass, is_redefinable);
395 }
396 
397 template <RedefinitionType kType>
CanRedefineClass(jclass klass,std::string * error_msg)398 jvmtiError Redefiner::CanRedefineClass(jclass klass, /*out*/ std::string* error_msg) {
399   art::Thread* self = art::Thread::Current();
400   art::ScopedObjectAccess soa(self);
401   art::StackHandleScope<1> hs(self);
402   art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
403   if (obj.IsNull() || !obj->IsClass()) {
404     return ERR(INVALID_CLASS);
405   }
406   art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
407   return Redefiner::CanRedefineClass<kType>(h_klass, error_msg);
408 }
409 
410 template <RedefinitionType kType>
CanRedefineClass(art::Handle<art::mirror::Class> klass,std::string * error_msg)411 jvmtiError Redefiner::CanRedefineClass(art::Handle<art::mirror::Class> klass,
412                                        /*out*/ std::string* error_msg) {
413   art::Thread* self = art::Thread::Current();
414   if (!klass->IsResolved()) {
415     // It's only a problem to try to retransform/redefine a unprepared class if it's happening on
416     // the same thread as the class-linking process. If it's on another thread we will be able to
417     // wait for the preparation to finish and continue from there.
418     if (klass->GetLockOwnerThreadId() == self->GetThreadId()) {
419       *error_msg = "Modification of class " + klass->PrettyClass() +
420           " from within the classes ClassLoad callback is not supported to prevent deadlocks." +
421           " Please use ClassFileLoadHook directly instead.";
422       return ERR(INTERNAL);
423     } else {
424       LOG(WARNING) << klass->PrettyClass() << " is not yet resolved. Attempting to transform "
425                    << "it could cause arbitrary length waits as the class is being resolved.";
426     }
427   }
428   if (klass->IsPrimitive()) {
429     *error_msg = "Modification of primitive classes is not supported";
430     return ERR(UNMODIFIABLE_CLASS);
431   } else if (klass->IsInterface()) {
432     *error_msg = "Modification of Interface classes is currently not supported";
433     return ERR(UNMODIFIABLE_CLASS);
434   } else if (klass->IsStringClass()) {
435     *error_msg = "Modification of String class is not supported";
436     return ERR(UNMODIFIABLE_CLASS);
437   } else if (klass->IsArrayClass()) {
438     *error_msg = "Modification of Array classes is not supported";
439     return ERR(UNMODIFIABLE_CLASS);
440   } else if (klass->IsProxyClass()) {
441     *error_msg = "Modification of proxy classes is not supported";
442     return ERR(UNMODIFIABLE_CLASS);
443   }
444 
445   for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
446     if (klass.Get() == self->DecodeJObject(c)->AsClass()) {
447       *error_msg = "Class might have stack frames that cannot be made obsolete";
448       return ERR(UNMODIFIABLE_CLASS);
449     }
450   }
451 
452   if (kType == RedefinitionType::kStructural) {
453     // Class initialization interacts really badly with structural redefinition since we need to
454     // make the old class obsolete. We currently just blanket don't allow it.
455     // TODO It might be nice to allow this at some point.
456     if (klass->IsInitializing() &&
457        !klass->IsInitialized() &&
458         klass->GetClinitThreadId() == self->GetTid()) {
459       // We are in the class-init running on this thread.
460       *error_msg = "Modification of class " + klass->PrettyClass() + " during class" +
461                    " initialization is not allowed.";
462       return ERR(INTERNAL);
463     }
464     if (!art::Runtime::Current()->GetClassLinker()->EnsureInitialized(
465             self, klass, /*can_init_fields=*/true, /*can_init_parents=*/true)) {
466       self->AssertPendingException();
467       *error_msg = "Class " + klass->PrettyClass() + " failed initialization. Structural" +
468                    " redefinition of erroneous classes is not allowed. Failure was: " +
469                    self->GetException()->Dump();
470       self->ClearException();
471       return ERR(INVALID_CLASS);
472     }
473     if (klass->IsMirrored()) {
474       std::string pc(klass->PrettyClass());
475       *error_msg = StringPrintf("Class %s is a mirror class and cannot be structurally redefined.",
476                                 pc.c_str());
477       return ERR(UNMODIFIABLE_CLASS);
478     }
479     // Check Thread specifically since it's not a root but too many things reach into it with Unsafe
480     // too allow structural redefinition.
481     if (klass->IsAssignableFrom(art::WellKnownClasses::java_lang_Thread.Get())) {
482       *error_msg =
483           "java.lang.Thread has fields accessed using sun.misc.unsafe directly. It is not "
484           "safe to structurally redefine it.";
485       return ERR(UNMODIFIABLE_CLASS);
486     }
487     auto has_pointer_marker =
488         [](art::ObjPtr<art::mirror::Class> k) REQUIRES_SHARED(art::Locks::mutator_lock_) {
489           // Check for fields/methods which were returned before moving to index jni id type.
490           // TODO We might want to rework how this is done. Once full redefinition is implemented we
491           // will need to check any subtypes too.
492           art::ObjPtr<art::mirror::ClassExt> ext(k->GetExtData());
493           if (!ext.IsNull()) {
494             if (ext->HasInstanceFieldPointerIdMarker() || ext->HasMethodPointerIdMarker() ||
495                 ext->HasStaticFieldPointerIdMarker()) {
496               return true;
497             }
498           }
499           return false;
500         };
501     if (has_pointer_marker(klass.Get())) {
502       *error_msg =
503           StringPrintf("%s has active pointer jni-ids and cannot be redefined structurally",
504                        klass->PrettyClass().c_str());
505       return ERR(UNMODIFIABLE_CLASS);
506     }
507     jvmtiError res = OK;
508     art::ClassFuncVisitor cfv(
509       [&](art::ObjPtr<art::mirror::Class> k) REQUIRES_SHARED(art::Locks::mutator_lock_) {
510         // if there is any class 'K' that is a subtype (i.e. extends) klass and has pointer-jni-ids
511         // we cannot structurally redefine the class 'k' since we would structurally redefine the
512         // subtype.
513         if (k->IsLoaded() && klass->IsAssignableFrom(k) && has_pointer_marker(k)) {
514           *error_msg = StringPrintf(
515               "%s has active pointer jni-ids from subtype %s and cannot be redefined structurally",
516               klass->PrettyClass().c_str(),
517               k->PrettyClass().c_str());
518           res = ERR(UNMODIFIABLE_CLASS);
519           return false;
520         }
521         return true;
522       });
523     art::Runtime::Current()->GetClassLinker()->VisitClasses(&cfv);
524     return res;
525   }
526   return OK;
527 }
528 
529 template jvmtiError Redefiner::CanRedefineClass<RedefinitionType::kNormal>(
530     art::Handle<art::mirror::Class> klass, /*out*/ std::string* error_msg);
531 template jvmtiError Redefiner::CanRedefineClass<RedefinitionType::kStructural>(
532     art::Handle<art::mirror::Class> klass, /*out*/ std::string* error_msg);
533 
534 // Moves dex data to an anonymous, read-only mmap'd region.
MoveDataToMemMap(const std::string & original_location,art::ArrayRef<const unsigned char> data,std::string * error_msg)535 art::MemMap Redefiner::MoveDataToMemMap(const std::string& original_location,
536                                         art::ArrayRef<const unsigned char> data,
537                                         std::string* error_msg) {
538   std::string modified_location = StringPrintf("%s-transformed", original_location.c_str());
539   // A dangling multi-dex location appended to bootclasspath can cause inaccuracy in oat file
540   // validation. For simplicity, just convert it to a normal location.
541   size_t pos = modified_location.find(art::DexFileLoader::kMultiDexSeparator);
542   if (pos != std::string::npos) {
543     modified_location[pos] = '-';
544   }
545   art::MemMap map = art::MemMap::MapAnonymous(
546       modified_location.c_str(),
547       data.size(),
548       PROT_READ|PROT_WRITE,
549       /*low_4gb=*/ false,
550       error_msg);
551   if (LIKELY(map.IsValid())) {
552     memcpy(map.Begin(), data.data(), data.size());
553     // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
554     // programs from corrupting it.
555     map.Protect(PROT_READ);
556   }
557   return map;
558 }
559 
ClassRedefinition(Redefiner * driver,jclass klass,const art::DexFile * redefined_dex_file,const char * class_sig,art::ArrayRef<const unsigned char> orig_dex_file)560 Redefiner::ClassRedefinition::ClassRedefinition(
561     Redefiner* driver,
562     jclass klass,
563     const art::DexFile* redefined_dex_file,
564     const char* class_sig,
565     art::ArrayRef<const unsigned char> orig_dex_file) :
566       driver_(driver),
567       klass_(klass),
568       dex_file_(redefined_dex_file),
569       class_sig_(class_sig),
570       original_dex_file_(orig_dex_file) {
571 }
572 
~ClassRedefinition()573 Redefiner::ClassRedefinition::~ClassRedefinition() {
574   if (art::kIsDebugBuild) {
575     if (dex_file_ != nullptr) {
576       art::Thread* self = art::Thread::Current();
577       art::ClassLinker* cl = art::Runtime::Current()->GetClassLinker();
578       CHECK(!cl->IsDexFileRegistered(self, *dex_file_));
579     }
580   }
581 }
582 
583 template<RedefinitionType kType>
RedefineClassesGeneric(jvmtiEnv * jenv,jint class_count,const jvmtiClassDefinition * definitions)584 jvmtiError Redefiner::RedefineClassesGeneric(jvmtiEnv* jenv,
585                                              jint class_count,
586                                              const jvmtiClassDefinition* definitions) {
587   art::Runtime* runtime = art::Runtime::Current();
588   art::Thread* self = art::Thread::Current();
589   ArtJvmTiEnv* env = ArtJvmTiEnv::AsArtJvmTiEnv(jenv);
590   if (env == nullptr) {
591     JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE env was null!";
592     return ERR(INVALID_ENVIRONMENT);
593   } else if (class_count < 0) {
594     JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE class_count was less then 0";
595     return ERR(ILLEGAL_ARGUMENT);
596   } else if (class_count == 0) {
597     // We don't actually need to do anything. Just return OK.
598     return OK;
599   } else if (definitions == nullptr) {
600     JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE null definitions!";
601     return ERR(NULL_POINTER);
602   }
603   std::string error_msg;
604   std::vector<ArtClassDefinition> def_vector;
605   def_vector.reserve(class_count);
606   for (jint i = 0; i < class_count; i++) {
607     jvmtiError res =
608         Redefiner::CanRedefineClass<RedefinitionType::kNormal>(definitions[i].klass, &error_msg);
609     if (res != OK) {
610       JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE " << error_msg;
611       return res;
612     }
613     ArtClassDefinition def;
614     res = def.Init(self, definitions[i]);
615     if (res != OK) {
616       JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE bad definition " << i;
617       return res;
618     }
619     def_vector.push_back(std::move(def));
620   }
621 
622   // Call necessary hooks. According to the spec we should send class file load hooks here. We
623   // handle it slightly differently to support structural redefinition. Look at the comments
624   // in Transformer::CallClassFileLoadHooks for more details.
625   Transformer::CallClassFileLoadHooks<kType>(self, &def_vector);
626 
627   jvmtiError res = RedefineClassesDirect(env, runtime, self, def_vector, kType, &error_msg);
628   if (res != OK) {
629     JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE " << error_msg;
630   }
631   return res;
632 }
633 
StructurallyRedefineClasses(jvmtiEnv * jenv,jint class_count,const jvmtiClassDefinition * definitions)634 jvmtiError Redefiner::StructurallyRedefineClasses(jvmtiEnv* jenv,
635                                                   jint class_count,
636                                                   const jvmtiClassDefinition* definitions) {
637   ArtJvmTiEnv* art_env = ArtJvmTiEnv::AsArtJvmTiEnv(jenv);
638   if (art_env == nullptr) {
639     return ERR(INVALID_ENVIRONMENT);
640   } else if (art_env->capabilities.can_redefine_classes != 1) {
641     return ERR(MUST_POSSESS_CAPABILITY);
642   }
643   return RedefineClassesGeneric<RedefinitionType::kStructural>(jenv, class_count, definitions);
644 }
645 
RedefineClasses(jvmtiEnv * jenv,jint class_count,const jvmtiClassDefinition * definitions)646 jvmtiError Redefiner::RedefineClasses(jvmtiEnv* jenv,
647                                       jint class_count,
648                                       const jvmtiClassDefinition* definitions) {
649   return RedefineClassesGeneric<RedefinitionType::kNormal>(jenv, class_count, definitions);
650 }
651 
RedefineClassesDirect(ArtJvmTiEnv * env,art::Runtime * runtime,art::Thread * self,const std::vector<ArtClassDefinition> & definitions,RedefinitionType type,std::string * error_msg)652 jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
653                                             art::Runtime* runtime,
654                                             art::Thread* self,
655                                             const std::vector<ArtClassDefinition>& definitions,
656                                             RedefinitionType type,
657                                             std::string* error_msg) {
658   DCHECK(env != nullptr);
659   if (definitions.size() == 0) {
660     // We don't actually need to do anything. Just return OK.
661     return OK;
662   }
663   // We need to fiddle with the verification class flags. To do this we need to make sure there are
664   // no concurrent redefinitions of the same class at the same time. For simplicity and because
665   // this is not expected to be a common occurrence we will just wrap the whole thing in a TOP-level
666   // lock.
667   Redefiner r(env, runtime, self, type, error_msg);
668   if (!canHandleRedefinition(self)) {
669     r.RecordFailure(ERR(INTERNAL), "Another redefinition is in progress");
670     return r.result_;
671   }
672 
673   // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
674   // are going to redefine.
675   // TODO We should prevent user-code suspensions to make sure this isn't held for too long.
676   art::jit::ScopedJitSuspend suspend_jit;
677   // Get shared mutator lock so we can lock all the classes.
678   art::ScopedObjectAccess soa(self);
679   for (const ArtClassDefinition& def : definitions) {
680     // Only try to transform classes that have been modified.
681     if (def.IsModified()) {
682       jvmtiError res = r.AddRedefinition(env, def);
683       if (res != OK) {
684         finishRedefinition(self);
685         return res;
686       }
687     }
688   }
689   jvmtiError res = r.Run();
690   finishRedefinition(self);
691   return res;
692 }
693 
AddRedefinition(ArtJvmTiEnv * env,const ArtClassDefinition & def)694 jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
695   std::string original_dex_location;
696   jvmtiError ret = OK;
697   if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
698     *error_msg_ = "Unable to get original dex file location!";
699     return ret;
700   }
701   char* generic_ptr_unused = nullptr;
702   char* signature_ptr = nullptr;
703   if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
704     *error_msg_ = "Unable to get class signature!";
705     return ret;
706   }
707   JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
708   JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
709   art::MemMap map = MoveDataToMemMap(original_dex_location, def.GetDexData(), error_msg_);
710   std::ostringstream os;
711   if (!map.IsValid()) {
712     os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
713        << "in dex file " << original_dex_location << " because: " << *error_msg_;
714     *error_msg_ = os.str();
715     return ERR(OUT_OF_MEMORY);
716   }
717   if (map.Size() < sizeof(art::DexFile::Header)) {
718     *error_msg_ = "Could not read dex file header because dex_data was too short";
719     return ERR(INVALID_CLASS_FORMAT);
720   }
721   std::string name = map.GetName();
722   uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
723   art::ArtDexFileLoader dex_file_loader(std::move(map), name);
724   std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(checksum,
725                                                                     /*verify=*/true,
726                                                                     /*verify_checksum=*/true,
727                                                                     error_msg_));
728   if (dex_file.get() == nullptr) {
729     os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
730     *error_msg_ = os.str();
731     return ERR(INVALID_CLASS_FORMAT);
732   }
733   redefinitions_.push_back(
734       Redefiner::ClassRedefinition(this,
735                                    def.GetClass(),
736                                    dex_file.release(),
737                                    signature_ptr,
738                                    def.GetNewOriginalDexFile()));
739   return OK;
740 }
741 
GetMirrorClass()742 art::ObjPtr<art::mirror::Class> Redefiner::ClassRedefinition::GetMirrorClass() {
743   return driver_->self_->DecodeJObject(klass_)->AsClass();
744 }
745 
GetClassLoader()746 art::ObjPtr<art::mirror::ClassLoader> Redefiner::ClassRedefinition::GetClassLoader() {
747   return GetMirrorClass()->GetClassLoader();
748 }
749 
CreateNewDexCache(art::Handle<art::mirror::ClassLoader> loader)750 art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
751     art::Handle<art::mirror::ClassLoader> loader) {
752   art::StackHandleScope<2> hs(driver_->self_);
753   art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
754   art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
755       art::ObjPtr<art::mirror::DexCache>::DownCast(
756           art::GetClassRoot<art::mirror::DexCache>(cl)->AllocObject(driver_->self_))));
757   if (cache.IsNull()) {
758     driver_->self_->AssertPendingOOMException();
759     return nullptr;
760   }
761   art::Handle<art::mirror::String> location(hs.NewHandle(
762       cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
763   if (location.IsNull()) {
764     driver_->self_->AssertPendingOOMException();
765     return nullptr;
766   }
767   art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
768   cache->SetLocation(location.Get());
769   cache->Initialize(dex_file_.get(), loader.Get());
770   return cache.Get();
771 }
772 
RecordFailure(jvmtiError result,const std::string & class_sig,const std::string & error_msg)773 void Redefiner::RecordFailure(jvmtiError result,
774                               const std::string& class_sig,
775                               const std::string& error_msg) {
776   *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
777                              class_sig.c_str(),
778                              error_msg.c_str());
779   result_ = result;
780 }
781 
AllocateOrGetOriginalDexFile()782 art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
783   // If we have been specifically given a new set of bytes use that
784   if (original_dex_file_.size() != 0) {
785     return art::mirror::ByteArray::AllocateAndFill(
786         driver_->self_,
787         reinterpret_cast<const signed char*>(original_dex_file_.data()),
788         original_dex_file_.size()).Ptr();
789   }
790 
791   // See if we already have one set.
792   art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
793   if (!ext.IsNull()) {
794     art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
795     if (!old_original_dex_file.IsNull()) {
796       // We do. Use it.
797       return old_original_dex_file.Ptr();
798     }
799   }
800 
801   // return the current dex_cache which has the dex file in it.
802   art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
803   return current_dex_cache.Ptr();
804 }
805 
806 struct CallbackCtx {
807   ObsoleteMap* obsolete_map;
808   art::LinearAlloc* allocator;
809   std::unordered_set<art::ArtMethod*> obsolete_methods;
810 
CallbackCtxopenjdkjvmti::CallbackCtx811   explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
812       : obsolete_map(map), allocator(alloc) {}
813 };
814 
DoAllocateObsoleteMethodsCallback(art::Thread * t,void * vdata)815 void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
816   CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
817   ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
818                                                    data->allocator,
819                                                    data->obsolete_methods,
820                                                    data->obsolete_map);
821 }
822 
823 // This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
824 // updated so they will be run.
825 // TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
FindAndAllocateObsoleteMethods(art::ObjPtr<art::mirror::Class> art_klass)826 void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(
827     art::ObjPtr<art::mirror::Class> art_klass) {
828   DCHECK(!IsStructuralRedefinition());
829   art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
830   art::ObjPtr<art::mirror::ClassExt> ext = art_klass->GetExtData();
831   CHECK(ext->GetObsoleteMethods() != nullptr);
832   art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
833   // This holds pointers to the obsolete methods map fields which are updated as needed.
834   ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
835   CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
836   // Add all the declared methods to the map
837   for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
838     if (m.IsIntrinsic()) {
839       LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
840                    << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
841                    << "methods that have already been compiled.";
842     }
843     // It is possible to simply filter out some methods where they cannot really become obsolete,
844     // such as native methods and keep their original (possibly optimized) implementations. We don't
845     // do this, however, since we would need to mark these functions (still in the classes
846     // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
847     // from (for example about stack-frame size). Furthermore we would be unable to get some useful
848     // error checking from the interpreter which ensure we don't try to start executing obsolete
849     // methods.
850     ctx.obsolete_methods.insert(&m);
851   }
852   {
853     art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
854     art::ThreadList* list = art::Runtime::Current()->GetThreadList();
855     list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
856     // After we've done walking all threads' stacks and updating method pointers on them,
857     // update JIT data structures (used by the stack walk above) to point to the new methods.
858     art::jit::Jit* jit = art::Runtime::Current()->GetJit();
859     if (jit != nullptr) {
860       for (const ObsoleteMap::ObsoleteMethodPair& it : *ctx.obsolete_map) {
861         // Notify the JIT we are making this obsolete method. It will update the jit's internal
862         // structures to keep track of the new obsolete method.
863         jit->GetCodeCache()->MoveObsoleteMethod(it.old_method, it.obsolete_method);
864       }
865     }
866   }
867 }
868 
869 namespace {
870 template <typename T> struct SignatureType {};
871 template <> struct SignatureType<art::ArtField> { using type = std::string_view; };
872 template <> struct SignatureType<art::ArtMethod> { using type = art::Signature; };
873 
874 template <typename T> struct NameAndSignature {
875  public:
876   using SigType = typename SignatureType<T>::type;
877 
878   NameAndSignature(const art::DexFile* dex_file, uint32_t id);
879 
NameAndSignatureopenjdkjvmti::__anona0303fab0211::NameAndSignature880   NameAndSignature(const std::string_view& name, const SigType& sig) : name_(name), sig_(sig) {}
881 
operator ==openjdkjvmti::__anona0303fab0211::NameAndSignature882   bool operator==(const NameAndSignature<T>& o) const {
883     return name_ == o.name_ && sig_ == o.sig_;
884   }
885 
operator !=openjdkjvmti::__anona0303fab0211::NameAndSignature886   bool operator!=(const NameAndSignature<T>& o) const {
887     return !(*this == o);
888   }
889 
dumpopenjdkjvmti::__anona0303fab0211::NameAndSignature890   std::ostream& dump(std::ostream& os) const {
891     return os << "'" << name_ << "' (sig: " << sig_ << ")";
892   }
893 
ToStringopenjdkjvmti::__anona0303fab0211::NameAndSignature894   std::string ToString() const {
895     std::ostringstream os;
896     os << *this;
897     return os.str();
898   }
899 
900   std::string_view name_;
901   SigType sig_;
902 };
903 
904 template <typename T>
operator <<(std::ostream & os,const NameAndSignature<T> & nas)905 std::ostream& operator<<(std::ostream& os, const NameAndSignature<T>& nas) {
906   return nas.dump(os);
907 }
908 
909 using FieldNameAndSignature = NameAndSignature<art::ArtField>;
910 template <>
NameAndSignature(const art::DexFile * dex_file,uint32_t id)911 FieldNameAndSignature::NameAndSignature(const art::DexFile* dex_file, uint32_t id)
912     : FieldNameAndSignature(dex_file->GetFieldName(dex_file->GetFieldId(id)),
913                             dex_file->GetFieldTypeDescriptor(dex_file->GetFieldId(id))) {}
914 
915 using MethodNameAndSignature = NameAndSignature<art::ArtMethod>;
916 template <>
NameAndSignature(const art::DexFile * dex_file,uint32_t id)917 MethodNameAndSignature::NameAndSignature(const art::DexFile* dex_file, uint32_t id)
918     : MethodNameAndSignature(dex_file->GetMethodName(dex_file->GetMethodId(id)),
919                              dex_file->GetMethodSignature(dex_file->GetMethodId(id))) {}
920 
921 }  // namespace
922 
RecordNewMethodAdded()923 void Redefiner::ClassRedefinition::RecordNewMethodAdded() {
924   DCHECK(driver_->IsStructuralRedefinition());
925   added_methods_ = true;
926 }
RecordNewFieldAdded()927 void Redefiner::ClassRedefinition::RecordNewFieldAdded() {
928   DCHECK(driver_->IsStructuralRedefinition());
929   added_fields_ = true;
930 }
931 
CheckMethods()932 bool Redefiner::ClassRedefinition::CheckMethods() {
933   art::StackHandleScope<1> hs(driver_->self_);
934   art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
935   DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
936 
937   // Make sure we have the same number of methods (or the same or greater if we're structural).
938   art::ClassAccessor accessor(*dex_file_, dex_file_->GetClassDef(0));
939   uint32_t num_new_method = accessor.NumMethods();
940   uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
941   const bool is_structural = driver_->IsStructuralRedefinition();
942   if (!is_structural && num_new_method != num_old_method) {
943     bool bigger = num_new_method > num_old_method;
944     RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
945                          : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
946                   StringPrintf("Total number of declared methods changed from %d to %d",
947                                num_old_method,
948                                num_new_method));
949     return false;
950   }
951 
952   // Skip all of the fields. We should have already checked this.
953   // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
954   // files have the same number of methods, which means there must be an equal amount of additions
955   // and removals. We should have already checked the fields.
956   const art::DexFile& old_dex_file = h_klass->GetDexFile();
957   art::ClassAccessor old_accessor(old_dex_file, *h_klass->GetClassDef());
958   // We need this to check for methods going missing in structural cases.
959   std::vector<bool> seen_old_methods(
960       (kCheckAllMethodsSeenOnce || is_structural) ? old_accessor.NumMethods() : 0, false);
961   const auto old_methods = old_accessor.GetMethods();
962   for (const art::ClassAccessor::Method& new_method : accessor.GetMethods()) {
963     // Get the data on the method we are searching for
964     MethodNameAndSignature new_method_id(dex_file_.get(), new_method.GetIndex());
965     const auto old_iter =
966         std::find_if(old_methods.cbegin(), old_methods.cend(), [&](const auto& current_old_method) {
967           MethodNameAndSignature old_method_id(&old_dex_file, current_old_method.GetIndex());
968           return old_method_id == new_method_id;
969         });
970 
971     if (!new_method.IsStaticOrDirect()) {
972       RecordHasVirtualMembers();
973     }
974     if (old_iter == old_methods.cend()) {
975       if (is_structural) {
976         RecordNewMethodAdded();
977       } else {
978         RecordFailure(
979             ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
980             StringPrintf("Unknown virtual method %s was added!", new_method_id.ToString().c_str()));
981         return false;
982       }
983     } else if (new_method.GetAccessFlags() != old_iter->GetAccessFlags()) {
984       RecordFailure(
985           ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
986           StringPrintf("method %s had different access flags", new_method_id.ToString().c_str()));
987       return false;
988     } else if (kCheckAllMethodsSeenOnce || is_structural) {
989       // We only need this if we are structural.
990       size_t off = std::distance(old_methods.cbegin(), old_iter);
991       DCHECK(!seen_old_methods[off])
992           << "field at " << off << "("
993           << MethodNameAndSignature(&old_dex_file, old_iter->GetIndex()) << ") already seen?";
994       seen_old_methods[off] = true;
995     }
996   }
997   if ((kCheckAllMethodsSeenOnce || is_structural) &&
998       !std::all_of(seen_old_methods.cbegin(), seen_old_methods.cend(), [](auto x) { return x; })) {
999     DCHECK(is_structural) << "We should have hit an earlier failure before getting here!";
1000     auto first_fail =
1001         std::find_if(seen_old_methods.cbegin(), seen_old_methods.cend(), [](auto x) { return !x; });
1002     auto off = std::distance(seen_old_methods.cbegin(), first_fail);
1003     auto fail = old_methods.cbegin();
1004     std::advance(fail, off);
1005     RecordFailure(
1006         ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
1007         StringPrintf("Method %s missing!",
1008                      MethodNameAndSignature(&old_dex_file, fail->GetIndex()).ToString().c_str()));
1009     return false;
1010   }
1011   return true;
1012 }
1013 
CheckFields()1014 bool Redefiner::ClassRedefinition::CheckFields() {
1015   art::StackHandleScope<1> hs(driver_->self_);
1016   art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
1017   DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1018   art::ClassAccessor new_accessor(*dex_file_, dex_file_->GetClassDef(0));
1019 
1020   const art::DexFile& old_dex_file = h_klass->GetDexFile();
1021   art::ClassAccessor old_accessor(old_dex_file, *h_klass->GetClassDef());
1022   // Instance and static fields can be differentiated by their flags so no need to check them
1023   // separately.
1024   std::vector<bool> seen_old_fields(old_accessor.NumFields(), false);
1025   const auto old_fields = old_accessor.GetFields();
1026   for (const art::ClassAccessor::Field& new_field : new_accessor.GetFields()) {
1027     // Get the data on the method we are searching for
1028     FieldNameAndSignature new_field_id(dex_file_.get(), new_field.GetIndex());
1029     const auto old_iter =
1030         std::find_if(old_fields.cbegin(), old_fields.cend(), [&](const auto& old_iter) {
1031           FieldNameAndSignature old_field_id(&old_dex_file, old_iter.GetIndex());
1032           return old_field_id == new_field_id;
1033         });
1034     if (!new_field.IsStatic()) {
1035       RecordHasVirtualMembers();
1036     }
1037     if (old_iter == old_fields.cend()) {
1038       if (driver_->IsStructuralRedefinition()) {
1039         RecordNewFieldAdded();
1040       } else {
1041         RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
1042                       StringPrintf("Unknown field %s added!", new_field_id.ToString().c_str()));
1043         return false;
1044       }
1045     } else if (new_field.GetAccessFlags() != old_iter->GetAccessFlags()) {
1046       RecordFailure(
1047           ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
1048           StringPrintf("Field %s had different access flags", new_field_id.ToString().c_str()));
1049       return false;
1050     } else {
1051       size_t off = std::distance(old_fields.cbegin(), old_iter);
1052       DCHECK(!seen_old_fields[off])
1053           << "field at " << off << "(" << FieldNameAndSignature(&old_dex_file, old_iter->GetIndex())
1054           << ") already seen?";
1055       seen_old_fields[off] = true;
1056     }
1057   }
1058   if (!std::all_of(seen_old_fields.cbegin(), seen_old_fields.cend(), [](auto x) { return x; })) {
1059     auto first_fail =
1060         std::find_if(seen_old_fields.cbegin(), seen_old_fields.cend(), [](auto x) { return !x; });
1061     auto off = std::distance(seen_old_fields.cbegin(), first_fail);
1062     auto fail = old_fields.cbegin();
1063     std::advance(fail, off);
1064     RecordFailure(
1065         ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
1066         StringPrintf("Field %s is missing!",
1067                      FieldNameAndSignature(&old_dex_file, fail->GetIndex()).ToString().c_str()));
1068     return false;
1069   }
1070   return true;
1071 }
1072 
CheckClass()1073 bool Redefiner::ClassRedefinition::CheckClass() {
1074   art::StackHandleScope<1> hs(driver_->self_);
1075   // Easy check that only 1 class def is present.
1076   if (dex_file_->NumClassDefs() != 1) {
1077     RecordFailure(ERR(ILLEGAL_ARGUMENT),
1078                   StringPrintf("Expected 1 class def in dex file but found %d",
1079                                dex_file_->NumClassDefs()));
1080     return false;
1081   }
1082   // Get the ClassDef from the new DexFile.
1083   // Since the dex file has only a single class def the index is always 0.
1084   const art::dex::ClassDef& def = dex_file_->GetClassDef(0);
1085   // Get the class as it is now.
1086   art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
1087 
1088   // Check the access flags didn't change.
1089   if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
1090     RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
1091                   "Cannot change modifiers of class by redefinition");
1092     return false;
1093   }
1094 
1095   // Check class name.
1096   // These should have been checked by the dexfile verifier on load.
1097   DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
1098   const char* descriptor = dex_file_->GetTypeDescriptor(def.class_idx_);
1099   DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
1100   if (!current_class->DescriptorEquals(descriptor)) {
1101     std::string storage;
1102     RecordFailure(ERR(NAMES_DONT_MATCH),
1103                   StringPrintf("expected file to contain class called '%s' but found '%s'!",
1104                                current_class->GetDescriptor(&storage),
1105                                descriptor));
1106     return false;
1107   }
1108   if (current_class->IsObjectClass()) {
1109     if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
1110       RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
1111       return false;
1112     }
1113   } else {
1114     const char* super_descriptor = dex_file_->GetTypeDescriptor(def.superclass_idx_);
1115     DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
1116     if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
1117       RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
1118       return false;
1119     }
1120   }
1121   const art::dex::TypeList* interfaces = dex_file_->GetInterfacesList(def);
1122   if (interfaces == nullptr) {
1123     if (current_class->NumDirectInterfaces() != 0) {
1124       // TODO Support this for kStructural.
1125       RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
1126       return false;
1127     }
1128   } else {
1129     DCHECK(!current_class->IsProxyClass());
1130     const art::dex::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
1131     if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
1132       // TODO Support this for kStructural.
1133       RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
1134       return false;
1135     }
1136     // The order of interfaces is (barely) meaningful so we error if it changes.
1137     const art::DexFile& orig_dex_file = current_class->GetDexFile();
1138     for (uint32_t i = 0; i < interfaces->Size(); i++) {
1139       if (strcmp(
1140             dex_file_->GetTypeDescriptor(interfaces->GetTypeItem(i).type_idx_),
1141             orig_dex_file.GetTypeDescriptor(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
1142         RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
1143                       "Interfaces changed or re-ordered");
1144         return false;
1145       }
1146     }
1147   }
1148   return true;
1149 }
1150 
CheckRedefinable()1151 bool Redefiner::ClassRedefinition::CheckRedefinable() {
1152   std::string err;
1153   art::StackHandleScope<1> hs(driver_->self_);
1154 
1155   art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
1156   jvmtiError res;
1157   if (driver_->type_ == RedefinitionType::kStructural && this->IsStructuralRedefinition()) {
1158     res = Redefiner::CanRedefineClass<RedefinitionType::kStructural>(h_klass, &err);
1159   } else {
1160     res = Redefiner::CanRedefineClass<RedefinitionType::kNormal>(h_klass, &err);
1161   }
1162   if (res != OK) {
1163     RecordFailure(res, err);
1164     return false;
1165   } else {
1166     return true;
1167   }
1168 }
1169 
CheckRedefinitionIsValid()1170 bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
1171   return CheckClass() && CheckFields() && CheckMethods() && CheckRedefinable();
1172 }
1173 
1174 class RedefinitionDataIter;
1175 
1176 // A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
1177 // reasonable way. This adds no fields to the normal ObjectArray. By doing this we can avoid
1178 // having to deal with the fact that we need to hold an arbitrary number of references live.
1179 class RedefinitionDataHolder {
1180  public:
1181   enum DataSlot : int32_t {
1182     kSlotSourceClassLoader = 0,
1183     kSlotJavaDexFile = 1,
1184     kSlotNewDexFileCookie = 2,
1185     kSlotNewDexCache = 3,
1186     kSlotMirrorClass = 4,
1187     kSlotOrigDexFile = 5,
1188     kSlotOldObsoleteMethods = 6,
1189     kSlotOldDexCaches = 7,
1190     kSlotNewClassObject = 8,
1191     kSlotOldInstanceObjects = 9,
1192     kSlotNewInstanceObjects = 10,
1193     kSlotOldClasses = 11,
1194     kSlotNewClasses = 12,
1195 
1196     // Must be last one.
1197     kNumSlots = 13,
1198   };
1199 
1200   // This needs to have a HandleScope passed in that is capable of creating a new Handle without
1201   // overflowing. Only one handle will be created. This object has a lifetime identical to that of
1202   // the passed in handle-scope.
RedefinitionDataHolder(art::StackHandleScope<1> * hs,art::Runtime * runtime,art::Thread * self,std::vector<Redefiner::ClassRedefinition> * redefinitions)1203   RedefinitionDataHolder(art::StackHandleScope<1>* hs,
1204                          art::Runtime* runtime,
1205                          art::Thread* self,
1206                          std::vector<Redefiner::ClassRedefinition>* redefinitions)
1207       REQUIRES_SHARED(art::Locks::mutator_lock_) :
1208     arr_(hs->NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
1209         self,
1210         art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Object>>(runtime->GetClassLinker()),
1211         redefinitions->size() * kNumSlots))),
1212     redefinitions_(redefinitions),
1213     initialized_(redefinitions_->size(), false),
1214     actually_structural_(redefinitions_->size(), false),
1215     initial_structural_(redefinitions_->size(), false) {}
1216 
1217   ~RedefinitionDataHolder() REQUIRES_SHARED(art::Locks::mutator_lock_);
1218 
IsNull() const1219   bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1220     return arr_.IsNull();
1221   }
1222 
GetSourceClassLoader(jint klass_index) const1223   art::ObjPtr<art::mirror::ClassLoader> GetSourceClassLoader(jint klass_index) const
1224       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1225     return art::ObjPtr<art::mirror::ClassLoader>::DownCast(
1226         GetSlot(klass_index, kSlotSourceClassLoader));
1227   }
GetJavaDexFile(jint klass_index) const1228   art::ObjPtr<art::mirror::Object> GetJavaDexFile(jint klass_index) const
1229       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1230     return GetSlot(klass_index, kSlotJavaDexFile);
1231   }
GetNewDexFileCookie(jint klass_index) const1232   art::ObjPtr<art::mirror::LongArray> GetNewDexFileCookie(jint klass_index) const
1233       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1234     return art::ObjPtr<art::mirror::LongArray>::DownCast(
1235         GetSlot(klass_index, kSlotNewDexFileCookie));
1236   }
GetNewDexCache(jint klass_index) const1237   art::ObjPtr<art::mirror::DexCache> GetNewDexCache(jint klass_index) const
1238       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1239     return art::ObjPtr<art::mirror::DexCache>::DownCast(GetSlot(klass_index, kSlotNewDexCache));
1240   }
GetMirrorClass(jint klass_index) const1241   art::ObjPtr<art::mirror::Class> GetMirrorClass(jint klass_index) const
1242       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1243     return art::ObjPtr<art::mirror::Class>::DownCast(GetSlot(klass_index, kSlotMirrorClass));
1244   }
1245 
GetOriginalDexFile(jint klass_index) const1246   art::ObjPtr<art::mirror::Object> GetOriginalDexFile(jint klass_index) const
1247       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1248     return art::ObjPtr<art::mirror::Object>::DownCast(GetSlot(klass_index, kSlotOrigDexFile));
1249   }
1250 
GetOldObsoleteMethods(jint klass_index) const1251   art::ObjPtr<art::mirror::PointerArray> GetOldObsoleteMethods(jint klass_index) const
1252       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1253     return art::ObjPtr<art::mirror::PointerArray>::DownCast(
1254         GetSlot(klass_index, kSlotOldObsoleteMethods));
1255   }
1256 
GetOldDexCaches(jint klass_index) const1257   art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> GetOldDexCaches(
1258       jint klass_index) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1259     return art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>>::DownCast(
1260         GetSlot(klass_index, kSlotOldDexCaches));
1261   }
1262 
GetNewClassObject(jint klass_index) const1263   art::ObjPtr<art::mirror::Class> GetNewClassObject(jint klass_index) const
1264       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1265     return art::ObjPtr<art::mirror::Class>::DownCast(GetSlot(klass_index, kSlotNewClassObject));
1266   }
1267 
GetOldInstanceObjects(jint klass_index) const1268   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> GetOldInstanceObjects(
1269       jint klass_index) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1270     return art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>>::DownCast(
1271         GetSlot(klass_index, kSlotOldInstanceObjects));
1272   }
1273 
GetNewInstanceObjects(jint klass_index) const1274   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> GetNewInstanceObjects(
1275       jint klass_index) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1276     return art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>>::DownCast(
1277         GetSlot(klass_index, kSlotNewInstanceObjects));
1278   }
GetOldClasses(jint klass_index) const1279   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> GetOldClasses(jint klass_index) const
1280       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1281     return art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>>::DownCast(
1282         GetSlot(klass_index, kSlotOldClasses));
1283   }
GetNewClasses(jint klass_index) const1284   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> GetNewClasses(jint klass_index) const
1285       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1286     return art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>>::DownCast(
1287         GetSlot(klass_index, kSlotNewClasses));
1288   }
IsInitialized(jint klass_index)1289   bool IsInitialized(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1290     return initialized_[klass_index];
1291   }
IsActuallyStructural(jint klass_index)1292   bool IsActuallyStructural(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1293     return actually_structural_[klass_index];
1294   }
1295 
IsInitialStructural(jint klass_index)1296   bool IsInitialStructural(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1297     return initial_structural_[klass_index];
1298   }
1299 
SetSourceClassLoader(jint klass_index,art::ObjPtr<art::mirror::ClassLoader> loader)1300   void SetSourceClassLoader(jint klass_index, art::ObjPtr<art::mirror::ClassLoader> loader)
1301       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1302     SetSlot(klass_index, kSlotSourceClassLoader, loader);
1303   }
SetJavaDexFile(jint klass_index,art::ObjPtr<art::mirror::Object> dexfile)1304   void SetJavaDexFile(jint klass_index, art::ObjPtr<art::mirror::Object> dexfile)
1305       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1306     SetSlot(klass_index, kSlotJavaDexFile, dexfile);
1307   }
SetNewDexFileCookie(jint klass_index,art::ObjPtr<art::mirror::LongArray> cookie)1308   void SetNewDexFileCookie(jint klass_index, art::ObjPtr<art::mirror::LongArray> cookie)
1309       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1310     SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
1311   }
SetNewDexCache(jint klass_index,art::ObjPtr<art::mirror::DexCache> cache)1312   void SetNewDexCache(jint klass_index, art::ObjPtr<art::mirror::DexCache> cache)
1313       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1314     SetSlot(klass_index, kSlotNewDexCache, cache);
1315   }
SetMirrorClass(jint klass_index,art::ObjPtr<art::mirror::Class> klass)1316   void SetMirrorClass(jint klass_index, art::ObjPtr<art::mirror::Class> klass)
1317       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1318     SetSlot(klass_index, kSlotMirrorClass, klass);
1319   }
SetOriginalDexFile(jint klass_index,art::ObjPtr<art::mirror::Object> bytes)1320   void SetOriginalDexFile(jint klass_index, art::ObjPtr<art::mirror::Object> bytes)
1321       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1322     SetSlot(klass_index, kSlotOrigDexFile, bytes);
1323   }
SetOldObsoleteMethods(jint klass_index,art::ObjPtr<art::mirror::PointerArray> methods)1324   void SetOldObsoleteMethods(jint klass_index, art::ObjPtr<art::mirror::PointerArray> methods)
1325       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1326     SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
1327   }
SetOldDexCaches(jint klass_index,art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)1328   void SetOldDexCaches(jint klass_index,
1329                        art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)
1330       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1331     SetSlot(klass_index, kSlotOldDexCaches, caches);
1332   }
1333 
SetNewClassObject(jint klass_index,art::ObjPtr<art::mirror::Class> klass)1334   void SetNewClassObject(jint klass_index, art::ObjPtr<art::mirror::Class> klass)
1335       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1336     SetSlot(klass_index, kSlotNewClassObject, klass);
1337   }
1338 
SetOldInstanceObjects(jint klass_index,art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)1339   void SetOldInstanceObjects(jint klass_index,
1340                              art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)
1341       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1342     SetSlot(klass_index, kSlotOldInstanceObjects, objs);
1343   }
SetNewInstanceObjects(jint klass_index,art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)1344   void SetNewInstanceObjects(jint klass_index,
1345                              art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)
1346       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1347     SetSlot(klass_index, kSlotNewInstanceObjects, objs);
1348   }
SetOldClasses(jint klass_index,art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)1349   void SetOldClasses(jint klass_index,
1350                      art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)
1351       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1352     SetSlot(klass_index, kSlotOldClasses, klasses);
1353   }
SetNewClasses(jint klass_index,art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)1354   void SetNewClasses(jint klass_index,
1355                      art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)
1356       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1357     SetSlot(klass_index, kSlotNewClasses, klasses);
1358   }
SetInitialized(jint klass_index)1359   void SetInitialized(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1360     initialized_[klass_index] = true;
1361   }
SetActuallyStructural(jint klass_index)1362   void SetActuallyStructural(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1363     actually_structural_[klass_index] = true;
1364   }
SetInitialStructural(jint klass_index)1365   void SetInitialStructural(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1366     initial_structural_[klass_index] = true;
1367   }
Length() const1368   int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1369     return arr_->GetLength() / kNumSlots;
1370   }
1371 
GetRedefinitions()1372   std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
1373       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1374     return redefinitions_;
1375   }
1376 
operator ==(const RedefinitionDataHolder & other) const1377   bool operator==(const RedefinitionDataHolder& other) const
1378       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1379     return arr_.Get() == other.arr_.Get();
1380   }
1381 
operator !=(const RedefinitionDataHolder & other) const1382   bool operator!=(const RedefinitionDataHolder& other) const
1383       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1384     return !(*this == other);
1385   }
1386 
1387   RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
1388   RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
1389 
1390  private:
1391   mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
1392   std::vector<Redefiner::ClassRedefinition>* redefinitions_;
1393   // Used to mark a particular redefinition as fully initialized.
1394   std::vector<bool> initialized_;
1395   // Used to mark a redefinition as 'actually' structural. That is either the redefinition is
1396   // structural or a superclass is.
1397   std::vector<bool> actually_structural_;
1398   // Used to mark a redefinition as the initial structural redefinition. This redefinition will take
1399   // care of updating all of its subtypes.
1400   std::vector<bool> initial_structural_;
1401 
GetSlot(jint klass_index,DataSlot slot) const1402   art::ObjPtr<art::mirror::Object> GetSlot(jint klass_index, DataSlot slot) const
1403       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1404     DCHECK_LT(klass_index, Length());
1405     return arr_->Get((kNumSlots * klass_index) + slot);
1406   }
1407 
SetSlot(jint klass_index,DataSlot slot,art::ObjPtr<art::mirror::Object> obj)1408   void SetSlot(jint klass_index,
1409                DataSlot slot,
1410                art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1411     DCHECK(!art::Runtime::Current()->IsActiveTransaction());
1412     DCHECK_LT(klass_index, Length());
1413     arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
1414   }
1415 
1416   DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
1417 };
1418 
1419 class RedefinitionDataIter {
1420  public:
RedefinitionDataIter(int32_t idx,RedefinitionDataHolder & holder)1421   RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
1422 
1423   RedefinitionDataIter(const RedefinitionDataIter&) = default;
1424   RedefinitionDataIter(RedefinitionDataIter&&) = default;
1425   // Assignments are deleted because holder_ is a reference.
1426   RedefinitionDataIter& operator=(const RedefinitionDataIter&) = delete;
1427   RedefinitionDataIter& operator=(RedefinitionDataIter&&) = delete;
1428 
operator ==(const RedefinitionDataIter & other) const1429   bool operator==(const RedefinitionDataIter& other) const
1430       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1431     return idx_ == other.idx_ && holder_ == other.holder_;
1432   }
1433 
operator !=(const RedefinitionDataIter & other) const1434   bool operator!=(const RedefinitionDataIter& other) const
1435       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1436     return !(*this == other);
1437   }
1438 
operator ++()1439   RedefinitionDataIter operator++() {  // Value after modification.
1440     idx_++;
1441     return *this;
1442   }
1443 
operator ++(int)1444   RedefinitionDataIter operator++(int) {
1445     RedefinitionDataIter temp = *this;
1446     idx_++;
1447     return temp;
1448   }
1449 
operator +(ssize_t delta) const1450   RedefinitionDataIter operator+(ssize_t delta) const {
1451     RedefinitionDataIter temp = *this;
1452     temp += delta;
1453     return temp;
1454   }
1455 
operator +=(ssize_t delta)1456   RedefinitionDataIter& operator+=(ssize_t delta) {
1457     idx_ += delta;
1458     return *this;
1459   }
1460 
1461   // Compat for STL iterators.
operator *()1462   RedefinitionDataIter& operator*() {
1463     return *this;
1464   }
1465 
GetRedefinition()1466   Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1467     return (*holder_.GetRedefinitions())[idx_];
1468   }
1469 
GetHolder()1470   RedefinitionDataHolder& GetHolder() {
1471     return holder_;
1472   }
1473 
GetSourceClassLoader() const1474   art::ObjPtr<art::mirror::ClassLoader> GetSourceClassLoader() const
1475       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1476     return holder_.GetSourceClassLoader(idx_);
1477   }
GetJavaDexFile() const1478   art::ObjPtr<art::mirror::Object> GetJavaDexFile() const
1479       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1480     return holder_.GetJavaDexFile(idx_);
1481   }
GetNewDexFileCookie() const1482   art::ObjPtr<art::mirror::LongArray> GetNewDexFileCookie() const
1483       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1484     return holder_.GetNewDexFileCookie(idx_);
1485   }
GetNewDexCache() const1486   art::ObjPtr<art::mirror::DexCache> GetNewDexCache() const
1487       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1488     return holder_.GetNewDexCache(idx_);
1489   }
GetMirrorClass() const1490   art::ObjPtr<art::mirror::Class> GetMirrorClass() const
1491       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1492     return holder_.GetMirrorClass(idx_);
1493   }
GetOriginalDexFile() const1494   art::ObjPtr<art::mirror::Object> GetOriginalDexFile() const
1495       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1496     return holder_.GetOriginalDexFile(idx_);
1497   }
GetOldObsoleteMethods() const1498   art::ObjPtr<art::mirror::PointerArray> GetOldObsoleteMethods() const
1499       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1500     return holder_.GetOldObsoleteMethods(idx_);
1501   }
GetOldDexCaches() const1502   art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> GetOldDexCaches() const
1503       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1504     return holder_.GetOldDexCaches(idx_);
1505   }
1506 
GetNewClassObject() const1507   art::ObjPtr<art::mirror::Class> GetNewClassObject() const
1508       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1509     return holder_.GetNewClassObject(idx_);
1510   }
1511 
GetOldInstanceObjects() const1512   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> GetOldInstanceObjects() const
1513       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1514     return holder_.GetOldInstanceObjects(idx_);
1515   }
GetNewInstanceObjects() const1516   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> GetNewInstanceObjects() const
1517       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1518     return holder_.GetNewInstanceObjects(idx_);
1519   }
GetOldClasses() const1520   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> GetOldClasses() const
1521       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1522     return holder_.GetOldClasses(idx_);
1523   }
GetNewClasses() const1524   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> GetNewClasses() const
1525       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1526     return holder_.GetNewClasses(idx_);
1527   }
IsInitialized() const1528   bool IsInitialized() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1529     return holder_.IsInitialized(idx_);
1530   }
IsActuallyStructural() const1531   bool IsActuallyStructural() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1532     return holder_.IsActuallyStructural(idx_);
1533   }
IsInitialStructural() const1534   bool IsInitialStructural() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1535     return holder_.IsInitialStructural(idx_);
1536   }
GetIndex() const1537   int32_t GetIndex() const {
1538     return idx_;
1539   }
1540 
SetSourceClassLoader(art::mirror::ClassLoader * loader)1541   void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1542       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1543     holder_.SetSourceClassLoader(idx_, loader);
1544   }
SetJavaDexFile(art::ObjPtr<art::mirror::Object> dexfile)1545   void SetJavaDexFile(art::ObjPtr<art::mirror::Object> dexfile)
1546       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1547     holder_.SetJavaDexFile(idx_, dexfile);
1548   }
SetNewDexFileCookie(art::ObjPtr<art::mirror::LongArray> cookie)1549   void SetNewDexFileCookie(art::ObjPtr<art::mirror::LongArray> cookie)
1550       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1551     holder_.SetNewDexFileCookie(idx_, cookie);
1552   }
SetNewDexCache(art::ObjPtr<art::mirror::DexCache> cache)1553   void SetNewDexCache(art::ObjPtr<art::mirror::DexCache> cache)
1554       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1555     holder_.SetNewDexCache(idx_, cache);
1556   }
SetMirrorClass(art::ObjPtr<art::mirror::Class> klass)1557   void SetMirrorClass(art::ObjPtr<art::mirror::Class> klass)
1558       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1559     holder_.SetMirrorClass(idx_, klass);
1560   }
SetOriginalDexFile(art::ObjPtr<art::mirror::Object> bytes)1561   void SetOriginalDexFile(art::ObjPtr<art::mirror::Object> bytes)
1562       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1563     holder_.SetOriginalDexFile(idx_, bytes);
1564   }
SetOldObsoleteMethods(art::ObjPtr<art::mirror::PointerArray> methods)1565   void SetOldObsoleteMethods(art::ObjPtr<art::mirror::PointerArray> methods)
1566       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1567     holder_.SetOldObsoleteMethods(idx_, methods);
1568   }
SetOldDexCaches(art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)1569   void SetOldDexCaches(art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)
1570       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1571     holder_.SetOldDexCaches(idx_, caches);
1572   }
SetNewClassObject(art::ObjPtr<art::mirror::Class> klass)1573   void SetNewClassObject(art::ObjPtr<art::mirror::Class> klass)
1574       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1575     holder_.SetNewClassObject(idx_, klass);
1576   }
SetOldInstanceObjects(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)1577   void SetOldInstanceObjects(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)
1578       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1579     holder_.SetOldInstanceObjects(idx_, objs);
1580   }
SetNewInstanceObjects(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)1581   void SetNewInstanceObjects(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)
1582       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1583     holder_.SetNewInstanceObjects(idx_, objs);
1584   }
SetOldClasses(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)1585   void SetOldClasses(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)
1586       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1587     holder_.SetOldClasses(idx_, klasses);
1588   }
SetNewClasses(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)1589   void SetNewClasses(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)
1590       REQUIRES_SHARED(art::Locks::mutator_lock_) {
1591     holder_.SetNewClasses(idx_, klasses);
1592   }
SetInitialized()1593   void SetInitialized() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1594     holder_.SetInitialized(idx_);
1595   }
SetActuallyStructural()1596   void SetActuallyStructural() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1597     holder_.SetActuallyStructural(idx_);
1598   }
SetInitialStructural()1599   void SetInitialStructural() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1600     holder_.SetInitialStructural(idx_);
1601   }
1602 
1603  private:
1604   int32_t idx_;
1605   RedefinitionDataHolder& holder_;
1606 };
1607 
begin()1608 RedefinitionDataIter RedefinitionDataHolder::begin() {
1609   return RedefinitionDataIter(0, *this);
1610 }
1611 
end()1612 RedefinitionDataIter RedefinitionDataHolder::end() {
1613   return RedefinitionDataIter(Length(), *this);
1614 }
1615 
~RedefinitionDataHolder()1616 RedefinitionDataHolder::~RedefinitionDataHolder() {
1617   art::Thread* self = art::Thread::Current();
1618   art::ClassLinker* cl = art::Runtime::Current()->GetClassLinker();
1619   for (RedefinitionDataIter data = begin(); data != end(); ++data) {
1620     art::ObjPtr<art::mirror::DexCache> dex_cache = data.GetNewDexCache();
1621     // When redefinition fails, the dex file will be deleted in the
1622     // `ClassRedefinition` destructor. To avoid having a heap `DexCache` pointing
1623     // to a dangling pointer, we clear the entries of those dex caches that are
1624     // not registered in the runtime.
1625     if (dex_cache != nullptr &&
1626         dex_cache->GetDexFile() != nullptr &&
1627         !cl->IsDexFileRegistered(self, *dex_cache->GetDexFile())) {
1628       dex_cache->ResetNativeArrays();
1629       dex_cache->SetDexFile(nullptr);
1630     }
1631   }
1632 }
1633 
CheckVerification(const RedefinitionDataIter & iter)1634 bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
1635   DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1636   art::StackHandleScope<3> hs(driver_->self_);
1637   std::string error;
1638   // TODO Make verification log level lower
1639   art::verifier::FailureKind failure =
1640       art::verifier::ClassVerifier::VerifyClass(driver_->self_,
1641                                                 /*verifier_deps=*/nullptr,
1642                                                 dex_file_.get(),
1643                                                 hs.NewHandle(iter.GetNewClassObject() != nullptr
1644                                                                 ? iter.GetNewClassObject()
1645                                                                 : iter.GetMirrorClass()),
1646                                                 hs.NewHandle(iter.GetNewDexCache()),
1647                                                 hs.NewHandle(GetClassLoader()),
1648                                                 /*class_def=*/ dex_file_->GetClassDef(0),
1649                                                 /*callbacks=*/ nullptr,
1650                                                 /*log_level=*/
1651                                                 art::verifier::HardFailLogMode::kLogWarning,
1652                                                 art::Runtime::Current()->GetTargetSdkVersion(),
1653                                                 &error);
1654   if (failure == art::verifier::FailureKind::kHardFailure) {
1655     RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1656     return false;
1657   }
1658   return true;
1659 }
1660 
1661 // Looks through the previously allocated cookies to see if we need to update them with another new
1662 // dexfile. This is so that even if multiple classes with the same classloader are redefined at
1663 // once they are all added to the classloader.
AllocateAndRememberNewDexFileCookie(art::Handle<art::mirror::ClassLoader> source_class_loader,art::Handle<art::mirror::Object> dex_file_obj,RedefinitionDataIter * cur_data)1664 bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
1665     art::Handle<art::mirror::ClassLoader> source_class_loader,
1666     art::Handle<art::mirror::Object> dex_file_obj,
1667     /*out*/RedefinitionDataIter* cur_data) {
1668   art::StackHandleScope<2> hs(driver_->self_);
1669   art::MutableHandle<art::mirror::LongArray> old_cookie(
1670       hs.NewHandle<art::mirror::LongArray>(nullptr));
1671   bool has_older_cookie = false;
1672   // See if we already have a cookie that a previous redefinition got from the same classloader
1673   // and the same JavaDex file.
1674   for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1675     if (old_data.GetSourceClassLoader() == source_class_loader.Get() &&
1676         old_data.GetJavaDexFile() == dex_file_obj.Get()) {
1677       // Since every instance of this JavaDex file should have the same cookie associated with it we
1678       // can stop looking here.
1679       has_older_cookie = true;
1680       old_cookie.Assign(old_data.GetNewDexFileCookie());
1681       break;
1682     }
1683   }
1684   if (old_cookie.IsNull()) {
1685     // No older cookie. Get it directly from the dex_file_obj
1686     // We should not have seen this classloader elsewhere.
1687     CHECK(!has_older_cookie);
1688     old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1689   }
1690   // Use the old cookie to generate the new one with the new DexFile* added in.
1691   art::Handle<art::mirror::LongArray>
1692       new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1693                                                                           old_cookie,
1694                                                                           dex_file_.get())));
1695   // Make sure the allocation worked.
1696   if (new_cookie.IsNull()) {
1697     return false;
1698   }
1699 
1700   // Save the cookie.
1701   cur_data->SetNewDexFileCookie(new_cookie.Get());
1702   // If there are other copies of the same classloader and the same JavaDex file we need to
1703   // make sure that we all have the same cookie.
1704   if (has_older_cookie) {
1705     for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1706       // We will let the GC take care of the cookie we allocated for this one.
1707       if (old_data.GetSourceClassLoader() == source_class_loader.Get() &&
1708           old_data.GetJavaDexFile() == dex_file_obj.Get()) {
1709         old_data.SetNewDexFileCookie(new_cookie.Get());
1710       }
1711     }
1712   }
1713 
1714   return true;
1715 }
1716 
CompareClasses(art::ObjPtr<art::mirror::Class> l,art::ObjPtr<art::mirror::Class> r)1717 bool CompareClasses(art::ObjPtr<art::mirror::Class> l, art::ObjPtr<art::mirror::Class> r)
1718     REQUIRES_SHARED(art::Locks::mutator_lock_) {
1719   auto parents = [](art::ObjPtr<art::mirror::Class> c) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1720     uint32_t res = 0;
1721     while (!c->IsObjectClass()) {
1722       res++;
1723       c = c->GetSuperClass();
1724     }
1725     return res;
1726   };
1727   return parents(l.Ptr()) < parents(r.Ptr());
1728 }
1729 
CollectAndCreateNewInstances(RedefinitionDataIter * cur_data)1730 bool Redefiner::ClassRedefinition::CollectAndCreateNewInstances(
1731     /*out*/ RedefinitionDataIter* cur_data) {
1732   if (!cur_data->IsInitialStructural()) {
1733     // An earlier structural redefinition already remade all the instances.
1734     return true;
1735   }
1736   art::gc::Heap* heap = driver_->runtime_->GetHeap();
1737   art::VariableSizedHandleScope hs(driver_->self_);
1738   art::Handle<art::mirror::Class> old_klass(hs.NewHandle(cur_data->GetMirrorClass()));
1739   std::vector<art::Handle<art::mirror::Object>> old_instances;
1740   auto is_instance = [&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1741     return obj->InstanceOf(old_klass.Get());
1742   };
1743   heap->VisitObjects([&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1744     if (is_instance(obj)) {
1745       old_instances.push_back(hs.NewHandle(obj));
1746     }
1747   });
1748   VLOG(plugin) << "Collected " << old_instances.size() << " instances to recreate!";
1749   art::Handle<art::mirror::ObjectArray<art::mirror::Class>> old_classes_arr(
1750       hs.NewHandle(cur_data->GetOldClasses()));
1751   art::Handle<art::mirror::ObjectArray<art::mirror::Class>> new_classes_arr(
1752       hs.NewHandle(cur_data->GetNewClasses()));
1753   DCHECK_EQ(old_classes_arr->GetLength(), new_classes_arr->GetLength());
1754   DCHECK_GT(old_classes_arr->GetLength(), 0);
1755   art::Handle<art::mirror::Class> obj_array_class(
1756       hs.NewHandle(art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Object>>(
1757           driver_->runtime_->GetClassLinker())));
1758   art::Handle<art::mirror::ObjectArray<art::mirror::Object>> old_instances_arr(
1759       hs.NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
1760           driver_->self_, obj_array_class.Get(), old_instances.size())));
1761   if (old_instances_arr.IsNull()) {
1762     driver_->self_->AssertPendingOOMException();
1763     driver_->self_->ClearException();
1764     RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate old_instance arrays!");
1765     return false;
1766   }
1767   for (uint32_t i = 0; i < old_instances.size(); ++i) {
1768     old_instances_arr->Set(i, old_instances[i].Get());
1769   }
1770   cur_data->SetOldInstanceObjects(old_instances_arr.Get());
1771 
1772   art::Handle<art::mirror::ObjectArray<art::mirror::Object>> new_instances_arr(
1773       hs.NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
1774           driver_->self_, obj_array_class.Get(), old_instances.size())));
1775   if (new_instances_arr.IsNull()) {
1776     driver_->self_->AssertPendingOOMException();
1777     driver_->self_->ClearException();
1778     RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate new_instance arrays!");
1779     return false;
1780   }
1781   for (auto pair : art::ZipCount(art::IterationRange(old_instances.begin(), old_instances.end()))) {
1782     art::Handle<art::mirror::Object> hinstance(pair.first);
1783     int32_t i = pair.second;
1784     auto iterator = art::ZipLeft(old_classes_arr.Iterate<art::mirror::Class>(),
1785                                  new_classes_arr.Iterate<art::mirror::Class>());
1786     auto it = std::find_if(iterator.begin(),
1787                            iterator.end(),
1788                            [&](auto class_pair) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1789                              return class_pair.first == hinstance->GetClass();
1790                            });
1791     DCHECK(it != iterator.end()) << "Unable to find class pair for "
1792                                  << hinstance->GetClass()->PrettyClass() << " (instance " << i
1793                                  << ")";
1794     auto [_, new_type] = *it;
1795     // Make sure when allocating the new instance we don't add it's finalizer since we will directly
1796     // replace the old object in the finalizer reference. If we added it here to we would call
1797     // finalize twice.
1798     // NB If a type is changed from being non-finalizable to finalizable the finalizers on any
1799     //    objects created before the redefine will never be called. This is (sort of) allowable by
1800     //    the spec and greatly simplifies implementation.
1801     // TODO Make it so we will always call all finalizers, even if the object when it was created
1802     // wasn't finalizable. To do this we need to be careful of handling failure correctly and making
1803     // sure that objects aren't finalized multiple times and that instances of failed redefinitions
1804     // aren't finalized.
1805     art::ObjPtr<art::mirror::Object> new_instance(
1806         new_type->Alloc</*kIsInstrumented=*/true,
1807                         art::mirror::Class::AddFinalizer::kNoAddFinalizer,
1808                         /*kCheckAddFinalizer=*/false>(
1809             driver_->self_, driver_->runtime_->GetHeap()->GetCurrentAllocator()));
1810     if (new_instance.IsNull()) {
1811       driver_->self_->AssertPendingOOMException();
1812       driver_->self_->ClearException();
1813       std::string msg(
1814           StringPrintf("Could not allocate instance %d of %zu", i, old_instances.size()));
1815       RecordFailure(ERR(OUT_OF_MEMORY), msg);
1816       return false;
1817     }
1818     new_instances_arr->Set(i, new_instance);
1819   }
1820   cur_data->SetNewInstanceObjects(new_instances_arr.Get());
1821   return true;
1822 }
1823 
FinishRemainingCommonAllocations(RedefinitionDataIter * cur_data)1824 bool Redefiner::ClassRedefinition::FinishRemainingCommonAllocations(
1825     /*out*/RedefinitionDataIter* cur_data) {
1826   art::StackHandleScope<2> hs(driver_->self_);
1827   cur_data->SetMirrorClass(GetMirrorClass());
1828   // This shouldn't allocate
1829   art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
1830   // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1831   if (!art::ClassLinker::IsBootClassLoader(loader.Get())) {
1832     cur_data->SetSourceClassLoader(loader.Get());
1833     art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1834         ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
1835     cur_data->SetJavaDexFile(dex_file_obj.Get());
1836     if (dex_file_obj == nullptr) {
1837       RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1838       return false;
1839     }
1840     // Allocate the new dex file cookie.
1841     if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
1842       driver_->self_->AssertPendingOOMException();
1843       driver_->self_->ClearException();
1844       RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1845       return false;
1846     }
1847   }
1848   cur_data->SetNewDexCache(CreateNewDexCache(loader));
1849   if (cur_data->GetNewDexCache() == nullptr) {
1850     driver_->self_->AssertPendingException();
1851     driver_->self_->ClearException();
1852     RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1853     return false;
1854   }
1855 
1856   // We won't always need to set this field.
1857   cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1858   if (cur_data->GetOriginalDexFile() == nullptr) {
1859     driver_->self_->AssertPendingOOMException();
1860     driver_->self_->ClearException();
1861     RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1862     return false;
1863   }
1864   return true;
1865 }
1866 
FinishNewClassAllocations(RedefinitionDataHolder & holder,RedefinitionDataIter * cur_data)1867 bool Redefiner::ClassRedefinition::FinishNewClassAllocations(RedefinitionDataHolder &holder,
1868                                                              RedefinitionDataIter *cur_data) {
1869   if (cur_data->IsInitialized() || !cur_data->IsActuallyStructural()) {
1870     cur_data->SetInitialized();
1871     return true;
1872   }
1873 
1874   art::VariableSizedHandleScope hs(driver_->self_);
1875   // If we weren't the lowest structural redef the superclass would have already initialized us.
1876   CHECK(IsStructuralRedefinition());
1877   CHECK(cur_data->IsInitialStructural()) << "Should have already been initialized by supertype";
1878   auto setup_single_redefinition =
1879       [this](RedefinitionDataIter* data, art::Handle<art::mirror::Class> super_class)
1880           REQUIRES_SHARED(art::Locks::mutator_lock_) -> art::ObjPtr<art::mirror::Class> {
1881     art::StackHandleScope<3> chs(driver_->self_);
1882     art::Handle<art::mirror::Class> nc(
1883         chs.NewHandle(AllocateNewClassObject(chs.NewHandle(data->GetMirrorClass()),
1884                                              super_class,
1885                                              chs.NewHandle(data->GetNewDexCache()),
1886                                              /*dex_class_def_index*/ 0)));
1887     if (nc.IsNull()) {
1888       return nullptr;
1889     }
1890 
1891     data->SetNewClassObject(nc.Get());
1892     data->SetInitialized();
1893     return nc.Get();
1894   };
1895 
1896   std::vector<art::Handle<art::mirror::Class>> old_types;
1897   {
1898     art::gc::Heap* heap = driver_->runtime_->GetHeap();
1899     art::Handle<art::mirror::Class>
1900         old_klass(hs.NewHandle(cur_data->GetMirrorClass()));
1901     if (setup_single_redefinition(cur_data, hs.NewHandle(old_klass->GetSuperClass())).IsNull()) {
1902       return false;
1903     }
1904     auto is_subtype = [&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1905       // We've already waited for class defines to be finished and paused them. All classes should be
1906       // either resolved or error. We don't need to do anything with error classes, since they cannot
1907       // be accessed in any observable way.
1908       return obj->IsClass() && obj->AsClass()->IsResolved() &&
1909             old_klass->IsAssignableFrom(obj->AsClass());
1910     };
1911     heap->VisitObjects([&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1912       if (is_subtype(obj)) {
1913         old_types.push_back(hs.NewHandle(obj->AsClass()));
1914       }
1915     });
1916     DCHECK_GT(old_types.size(), 0u) << "Expected to find at least old_klass!";
1917     VLOG(plugin) << "Found " << old_types.size() << " types that are/are subtypes of "
1918                 << old_klass->PrettyClass();
1919   }
1920 
1921   art::Handle<art::mirror::Class> cls_array_class(
1922       hs.NewHandle(art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Class>>(
1923           driver_->runtime_->GetClassLinker())));
1924   art::Handle<art::mirror::ObjectArray<art::mirror::Class>> old_classes_arr(
1925       hs.NewHandle(art::mirror::ObjectArray<art::mirror::Class>::Alloc(
1926           driver_->self_, cls_array_class.Get(), old_types.size())));
1927   if (old_classes_arr.IsNull()) {
1928     driver_->self_->AssertPendingOOMException();
1929     driver_->self_->ClearException();
1930     RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate old_classes arrays!");
1931     return false;
1932   }
1933   // Sort the old_types topologically.
1934   {
1935     art::ScopedAssertNoThreadSuspension sants("Sort classes");
1936     // Sort them by the distance to the base-class. This ensures that any class occurs before any of
1937     // its subtypes.
1938     std::sort(old_types.begin(),
1939               old_types.end(),
1940               [](auto& l, auto& r) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1941                 return CompareClasses(l.Get(), r.Get());
1942               });
1943   }
1944   for (uint32_t i = 0; i < old_types.size(); ++i) {
1945     DCHECK(!old_types[i].IsNull()) << i;
1946     old_classes_arr->Set(i, old_types[i].Get());
1947   }
1948   cur_data->SetOldClasses(old_classes_arr.Get());
1949   DCHECK_GT(old_classes_arr->GetLength(), 0);
1950 
1951   art::Handle<art::mirror::ObjectArray<art::mirror::Class>> new_classes_arr(
1952       hs.NewHandle(art::mirror::ObjectArray<art::mirror::Class>::Alloc(
1953           driver_->self_, cls_array_class.Get(), old_types.size())));
1954   if (new_classes_arr.IsNull()) {
1955     driver_->self_->AssertPendingOOMException();
1956     driver_->self_->ClearException();
1957     RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate new_classes arrays!");
1958     return false;
1959   }
1960 
1961   art::MutableHandle<art::mirror::DexCache> dch(hs.NewHandle<art::mirror::DexCache>(nullptr));
1962   art::MutableHandle<art::mirror::Class> superclass(hs.NewHandle<art::mirror::Class>(nullptr));
1963   for (size_t i = 0; i < old_types.size(); i++) {
1964     art::Handle<art::mirror::Class>& old_type = old_types[i];
1965     if (old_type.Get() == cur_data->GetMirrorClass()) {
1966       CHECK_EQ(i, 0u) << "original class not at index 0. Bad sort!";
1967       new_classes_arr->Set(i, cur_data->GetNewClassObject());
1968       continue;
1969     } else {
1970       auto old_super = std::find_if(old_types.begin(),
1971                                     old_types.begin() + i,
1972                                     [&](art::Handle<art::mirror::Class>& v)
1973                                         REQUIRES_SHARED(art::Locks::mutator_lock_) {
1974                                           return v.Get() == old_type->GetSuperClass();
1975                                         });
1976       // Only the GetMirrorClass should not be in this list.
1977       CHECK(old_super != old_types.begin() + i)
1978           << "from first " << i << " could not find super of " << old_type->PrettyClass()
1979           << " expected to find " << old_type->GetSuperClass()->PrettyClass();
1980       superclass.Assign(new_classes_arr->Get(std::distance(old_types.begin(), old_super)));
1981       auto new_redef = std::find_if(
1982           *cur_data + 1, holder.end(), [&](auto it) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1983             return it.GetMirrorClass() == old_type.Get();
1984           });
1985       art::ObjPtr<art::mirror::Class> new_type;
1986       if (new_redef == holder.end()) {
1987         // We aren't also redefining this subclass. Just allocate a new class and continue.
1988         dch.Assign(old_type->GetDexCache());
1989         new_type =
1990             AllocateNewClassObject(old_type, superclass, dch, old_type->GetDexClassDefIndex());
1991       } else {
1992         // This subclass is also being redefined. We need to use its new dex-file to load the new
1993         // class.
1994         CHECK(new_redef.IsActuallyStructural());
1995         CHECK(!new_redef.IsInitialStructural());
1996         new_type = setup_single_redefinition(&new_redef, superclass);
1997       }
1998       if (new_type == nullptr) {
1999         VLOG(plugin) << "Failed to load new version of class " << old_type->PrettyClass()
2000                      << " for structural redefinition!";
2001         return false;
2002       }
2003       new_classes_arr->Set(i, new_type);
2004     }
2005   }
2006   cur_data->SetNewClasses(new_classes_arr.Get());
2007   return true;
2008 }
2009 
GetNewClassSize(art::ClassAccessor & accessor)2010 uint32_t Redefiner::ClassRedefinition::GetNewClassSize(art::ClassAccessor& accessor) {
2011   uint32_t num_8bit_static_fields = 0;
2012   uint32_t num_16bit_static_fields = 0;
2013   uint32_t num_32bit_static_fields = 0;
2014   uint32_t num_64bit_static_fields = 0;
2015   uint32_t num_ref_static_fields = 0;
2016   for (const art::ClassAccessor::Field& f : accessor.GetStaticFields()) {
2017     std::string_view desc(accessor.GetDexFile().GetFieldTypeDescriptor(
2018         accessor.GetDexFile().GetFieldId(f.GetIndex())));
2019     if (desc[0] == 'L' || desc[0] == '[') {
2020       num_ref_static_fields++;
2021     } else if (desc == "Z" || desc == "B") {
2022       num_8bit_static_fields++;
2023     } else if (desc == "C" || desc == "S") {
2024       num_16bit_static_fields++;
2025     } else if (desc == "I" || desc == "F") {
2026       num_32bit_static_fields++;
2027     } else if (desc == "J" || desc == "D") {
2028       num_64bit_static_fields++;
2029     } else {
2030       LOG(FATAL) << "Unknown type descriptor! " << desc;
2031     }
2032   }
2033 
2034   return art::mirror::Class::ComputeClassSize(/*has_embedded_vtable=*/ false,
2035                                               /*num_vtable_entries=*/ 0,
2036                                               num_8bit_static_fields,
2037                                               num_16bit_static_fields,
2038                                               num_32bit_static_fields,
2039                                               num_64bit_static_fields,
2040                                               num_ref_static_fields,
2041                                               art::kRuntimePointerSize);
2042 }
2043 
2044 art::ObjPtr<art::mirror::Class>
AllocateNewClassObject(art::Handle<art::mirror::DexCache> cache)2045 Redefiner::ClassRedefinition::AllocateNewClassObject(art::Handle<art::mirror::DexCache> cache) {
2046   art::StackHandleScope<2> hs(driver_->self_);
2047   art::Handle<art::mirror::Class> old_class(hs.NewHandle(GetMirrorClass()));
2048   art::Handle<art::mirror::Class> super_class(hs.NewHandle(old_class->GetSuperClass()));
2049   return AllocateNewClassObject(old_class, super_class, cache, /*dex_class_def_index*/0);
2050 }
2051 
AllocateNewClassObject(art::Handle<art::mirror::Class> old_class,art::Handle<art::mirror::Class> super_class,art::Handle<art::mirror::DexCache> cache,uint16_t dex_class_def_index)2052 art::ObjPtr<art::mirror::Class> Redefiner::ClassRedefinition::AllocateNewClassObject(
2053     art::Handle<art::mirror::Class> old_class,
2054     art::Handle<art::mirror::Class> super_class,
2055     art::Handle<art::mirror::DexCache> cache,
2056     uint16_t dex_class_def_index) {
2057   // This is a stripped down DefineClass. We don't want to use DefineClass directly because it needs
2058   // to perform a lot of extra steps to tell the ClassTable and the jit and everything about a new
2059   // class. For now we will need to rely on our tests catching any issues caused by changes in how
2060   // class_linker sets up classes.
2061   // TODO Unify/move this into ClassLinker maybe.
2062   art::StackHandleScope<3> hs(driver_->self_);
2063   art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
2064   const art::DexFile* dex_file = cache->GetDexFile();
2065   art::ClassAccessor accessor(*dex_file, dex_class_def_index);
2066   art::Handle<art::mirror::Class> new_class(hs.NewHandle(linker->AllocClass(
2067       driver_->self_, GetNewClassSize(accessor))));
2068   if (new_class.IsNull()) {
2069     driver_->self_->AssertPendingOOMException();
2070     RecordFailure(
2071         ERR(OUT_OF_MEMORY),
2072         "Unable to allocate class object for redefinition of " + old_class->PrettyClass());
2073     driver_->self_->ClearException();
2074     return nullptr;
2075   }
2076   new_class->SetDexCache(cache.Get());
2077   linker->SetupClass(*dex_file,
2078                      dex_file->GetClassDef(dex_class_def_index),
2079                      new_class,
2080                      old_class->GetClassLoader());
2081 
2082   // Make sure we are ready for linking. The lock isn't really needed since this isn't visible to
2083   // other threads but the linker expects it.
2084   art::ObjectLock<art::mirror::Class> lock(driver_->self_, new_class);
2085   new_class->SetClinitThreadId(driver_->self_->GetTid());
2086   // Make sure we have a valid empty iftable even if there are errors.
2087   new_class->SetIfTable(art::GetClassRoot<art::mirror::Object>(linker)->GetIfTable());
2088   linker->LoadClass(
2089       driver_->self_, *dex_file, dex_file->GetClassDef(dex_class_def_index), new_class);
2090   // NB. We know the interfaces and supers didn't change! :)
2091   art::MutableHandle<art::mirror::Class> linked_class(hs.NewHandle<art::mirror::Class>(nullptr));
2092   art::Handle<art::mirror::ObjectArray<art::mirror::Class>> proxy_ifaces(
2093       hs.NewHandle<art::mirror::ObjectArray<art::mirror::Class>>(nullptr));
2094   // No changing hierarchy so everything is loaded.
2095   new_class->SetSuperClass(super_class.Get());
2096   art::mirror::Class::SetStatus(new_class, art::ClassStatus::kLoaded, nullptr);
2097   if (!linker->LinkClass(driver_->self_, nullptr, new_class, proxy_ifaces, &linked_class)) {
2098     std::ostringstream oss;
2099     oss << "failed to link class due to "
2100         << (driver_->self_->IsExceptionPending() ? driver_->self_->GetException()->Dump()
2101                                                  : " unknown");
2102     RecordFailure(ERR(INTERNAL), oss.str());
2103     driver_->self_->ClearException();
2104     return nullptr;
2105   }
2106   // Everything is already resolved.
2107   art::ObjectLock<art::mirror::Class> objlock(driver_->self_, linked_class);
2108   // Mark the class as initialized.
2109   CHECK(old_class->IsResolved())
2110       << "Attempting to redefine an unresolved class " << old_class->PrettyClass()
2111       << " status=" << old_class->GetStatus();
2112   CHECK(linked_class->IsResolved());
2113   if (old_class->ShouldSkipHiddenApiChecks()) {
2114     // Match skip hiddenapi flag
2115     linked_class->SetSkipHiddenApiChecks();
2116   }
2117   if (old_class->IsInitialized()) {
2118     // We already verified the class earlier. No need to do it again.
2119     linker->ForceClassInitialized(driver_->self_, linked_class);
2120   } else if (old_class->GetStatus() > linked_class->GetStatus()) {
2121     // We want to match the old status.
2122     art::mirror::Class::SetStatus(linked_class, old_class->GetStatus(), driver_->self_);
2123   }
2124   // Make sure we have ext-data space for method & field ids. We won't know if we need them until
2125   // it's too late to create them.
2126   // TODO We might want to remove these arrays if they're not needed.
2127   if (!art::mirror::Class::EnsureInstanceFieldIds(linked_class) ||
2128       !art::mirror::Class::EnsureStaticFieldIds(linked_class) ||
2129       !art::mirror::Class::EnsureMethodIds(linked_class)) {
2130     driver_->self_->AssertPendingOOMException();
2131     driver_->self_->ClearException();
2132     RecordFailure(
2133         ERR(OUT_OF_MEMORY),
2134         "Unable to allocate jni-id arrays for redefinition of " + old_class->PrettyClass());
2135     return nullptr;
2136   }
2137   // Finish setting up methods.
2138   linked_class->VisitMethods([&](art::ArtMethod* m) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2139     driver_->runtime_->GetInstrumentation()->InitializeMethodsCode(m, /* aot_code= */ nullptr);
2140     m->SetNotIntrinsic();
2141     DCHECK(m->IsCopied() || m->GetDeclaringClass() == linked_class.Get())
2142         << m->PrettyMethod()
2143         << " m->GetDeclaringClass(): " << m->GetDeclaringClass()->PrettyClass()
2144         << " != linked_class.Get(): " << linked_class->PrettyClass();
2145   }, art::kRuntimePointerSize);
2146   if (art::kIsDebugBuild) {
2147     linked_class->VisitFields([&](art::ArtField* f) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2148       DCHECK_EQ(f->GetDeclaringClass(), linked_class.Get());
2149     });
2150   }
2151   // Reset ClinitThreadId back to the thread that loaded the old class. This is needed if we are in
2152   // the middle of initializing a class.
2153   linked_class->SetClinitThreadId(old_class->GetClinitThreadId());
2154   return linked_class.Get();
2155 }
2156 
UnregisterJvmtiBreakpoints()2157 void Redefiner::ClassRedefinition::UnregisterJvmtiBreakpoints() {
2158   BreakpointUtil::RemoveBreakpointsInClass(driver_->env_, GetMirrorClass().Ptr());
2159 }
2160 
UnregisterAllBreakpoints()2161 void Redefiner::UnregisterAllBreakpoints() {
2162   for (Redefiner::ClassRedefinition& redef : redefinitions_) {
2163     redef.UnregisterJvmtiBreakpoints();
2164   }
2165 }
2166 
CheckAllRedefinitionAreValid()2167 bool Redefiner::CheckAllRedefinitionAreValid() {
2168   for (Redefiner::ClassRedefinition& redef : redefinitions_) {
2169     if (!redef.CheckRedefinitionIsValid()) {
2170       return false;
2171     }
2172   }
2173   return true;
2174 }
2175 
RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder & holder)2176 void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
2177   for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2178     data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
2179   }
2180 }
2181 
MarkStructuralChanges(RedefinitionDataHolder & holder)2182 void Redefiner::MarkStructuralChanges(RedefinitionDataHolder& holder) {
2183   for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2184     if (data.IsActuallyStructural()) {
2185       // A superclass was structural and it marked all subclasses already. No need to do anything.
2186       CHECK(!data.IsInitialStructural());
2187     } else if (data.GetRedefinition().IsStructuralRedefinition()) {
2188       data.SetActuallyStructural();
2189       data.SetInitialStructural();
2190       // Go over all potential subtypes and mark any that are actually subclasses as structural.
2191       for (RedefinitionDataIter sub_data = data + 1; sub_data != holder.end(); ++sub_data) {
2192         if (sub_data.GetRedefinition().GetMirrorClass()->IsSubClass(
2193                 data.GetRedefinition().GetMirrorClass())) {
2194           sub_data.SetActuallyStructural();
2195         }
2196       }
2197     }
2198   }
2199 }
2200 
EnsureAllClassAllocationsFinished(RedefinitionDataHolder & holder)2201 bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
2202   for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2203     if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
2204       return false;
2205     }
2206   }
2207   return true;
2208 }
2209 
CollectAndCreateNewInstances(RedefinitionDataHolder & holder)2210 bool Redefiner::CollectAndCreateNewInstances(RedefinitionDataHolder& holder) {
2211   for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2212     // Allocate the data this redefinition requires.
2213     if (!data.GetRedefinition().CollectAndCreateNewInstances(&data)) {
2214       return false;
2215     }
2216   }
2217   return true;
2218 }
2219 
FinishAllNewClassAllocations(RedefinitionDataHolder & holder)2220 bool Redefiner::FinishAllNewClassAllocations(RedefinitionDataHolder& holder) {
2221   for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2222     // Allocate the data this redefinition requires.
2223     if (!data.GetRedefinition().FinishNewClassAllocations(holder, &data)) {
2224       return false;
2225     }
2226   }
2227   return true;
2228 }
2229 
FinishAllRemainingCommonAllocations(RedefinitionDataHolder & holder)2230 bool Redefiner::FinishAllRemainingCommonAllocations(RedefinitionDataHolder& holder) {
2231   for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2232     // Allocate the data this redefinition requires.
2233     if (!data.GetRedefinition().FinishRemainingCommonAllocations(&data)) {
2234       return false;
2235     }
2236   }
2237   return true;
2238 }
2239 
ReleaseDexFile()2240 void Redefiner::ClassRedefinition::ReleaseDexFile() {
2241   if (art::kIsDebugBuild) {
2242     art::Thread* self = art::Thread::Current();
2243     art::ClassLinker* cl = art::Runtime::Current()->GetClassLinker();
2244     CHECK(cl->IsDexFileRegistered(self, *dex_file_));
2245   }
2246   dex_file_.release();  // NOLINT b/117926937
2247 }
2248 
ReleaseAllDexFiles()2249 void Redefiner::ReleaseAllDexFiles() {
2250   for (Redefiner::ClassRedefinition& redef : redefinitions_) {
2251     redef.ReleaseDexFile();
2252   }
2253 }
2254 
CheckAllClassesAreVerified(RedefinitionDataHolder & holder)2255 bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
2256   for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2257     if (!data.GetRedefinition().CheckVerification(data)) {
2258       return false;
2259     }
2260   }
2261   return true;
2262 }
2263 
2264 class ScopedDisableConcurrentAndMovingGc {
2265  public:
ScopedDisableConcurrentAndMovingGc(art::gc::Heap * heap,art::Thread * self)2266   ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
2267       : heap_(heap), self_(self) {
2268     if (heap_->IsGcConcurrentAndMoving()) {
2269       heap_->IncrementDisableMovingGC(self_);
2270     }
2271   }
2272 
~ScopedDisableConcurrentAndMovingGc()2273   ~ScopedDisableConcurrentAndMovingGc() {
2274     if (heap_->IsGcConcurrentAndMoving()) {
2275       heap_->DecrementDisableMovingGC(self_);
2276     }
2277   }
2278  private:
2279   art::gc::Heap* heap_;
2280   art::Thread* self_;
2281 };
2282 
2283 class ClassDefinitionPauser : public art::ClassLoadCallback {
2284  public:
REQUIRES_SHARED(art::Locks::mutator_lock_)2285   explicit ClassDefinitionPauser(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_)
2286       : self_(self),
2287         is_running_(false),
2288         barrier_(0),
2289         release_mu_("SuspendClassDefinition lock", art::kGenericBottomLock),
2290         release_barrier_(0),
2291         release_cond_("SuspendClassDefinition condvar", release_mu_),
2292         count_(0),
2293         release_(false) {
2294     art::Locks::mutator_lock_->AssertSharedHeld(self_);
2295   }
REQUIRES_SHARED(art::Locks::mutator_lock_)2296   ~ClassDefinitionPauser() REQUIRES_SHARED(art::Locks::mutator_lock_) {
2297     art::Locks::mutator_lock_->AssertSharedHeld(self_);
2298     CHECK(release_) << "Must call Release()";
2299   }
Release()2300   void Release() REQUIRES(art::Locks::mutator_lock_) {
2301     if (is_running_) {
2302       art::Locks::mutator_lock_->AssertExclusiveHeld(self_);
2303       uint32_t count;
2304       // Wake up everything.
2305       {
2306         art::MutexLock mu(self_, release_mu_);
2307         release_ = true;
2308         // We have an exclusive mutator so all threads must be suspended and therefore they've
2309         // either already incremented this count_ or they are stuck somewhere before it.
2310         count = count_;
2311         release_cond_.Broadcast(self_);
2312       }
2313       // Wait for all threads to leave this structs code.
2314       VLOG(plugin) << "Resuming " << count << " threads paused before class-allocation!";
2315       release_barrier_.Increment</*locks=*/art::Barrier::kAllowHoldingLocks>(self_, count);
2316     } else {
2317       release_ = true;
2318     }
2319   }
BeginDefineClass()2320   void BeginDefineClass() override REQUIRES_SHARED(art::Locks::mutator_lock_) {
2321     art::Thread* this_thread = art::Thread::Current();
2322     if (this_thread == self_) {
2323       // Allow the redefining thread to do whatever.
2324       return;
2325     }
2326     if (this_thread->GetDefineClassCount() != 0) {
2327       // We are in the middle of a recursive define-class. Don't suspend now allow it to finish.
2328       VLOG(plugin) << "Recursive DefineClass in " << *this_thread
2329                    << " allowed to proceed despite class-def pause initiated by " << *self_;
2330       return;
2331     }
2332     // If we are suspended (no mutator-lock) then the pausing thread could do everything before the
2333     // count_++ including destroying this object, causing UAF/deadlock.
2334     art::Locks::mutator_lock_->AssertSharedHeld(this_thread);
2335     ++count_;
2336     art::ScopedThreadSuspension sts(this_thread, art::ThreadState::kSuspended);
2337     {
2338       art::MutexLock mu(this_thread, release_mu_);
2339       VLOG(plugin) << "Suspending " << *this_thread << " due to class definition. class-def pause "
2340                    << "initiated by " << *self_;
2341       while (!release_) {
2342         release_cond_.Wait(this_thread);
2343       }
2344     }
2345     release_barrier_.Pass(this_thread);
2346   }
2347 
EndDefineClass()2348   void EndDefineClass() override REQUIRES_SHARED(art::Locks::mutator_lock_) {
2349     art::Thread* this_thread = art::Thread::Current();
2350     if (this_thread == self_) {
2351       // Allow the redefining thread to do whatever.
2352       return;
2353     }
2354     if (this_thread->GetDefineClassCount() == 0) {
2355       // We are done with defining classes.
2356       barrier_.Pass(this_thread);
2357     }
2358   }
2359 
ClassLoad(art::Handle<art::mirror::Class> klass)2360   void ClassLoad([[maybe_unused]] art::Handle<art::mirror::Class> klass) override {}
ClassPrepare(art::Handle<art::mirror::Class> klass1,art::Handle<art::mirror::Class> klass2)2361   void ClassPrepare([[maybe_unused]] art::Handle<art::mirror::Class> klass1,
2362                     [[maybe_unused]] art::Handle<art::mirror::Class> klass2) override {}
2363 
SetRunning()2364   void SetRunning() {
2365     is_running_ = true;
2366   }
WaitFor(uint32_t t)2367   void WaitFor(uint32_t t) REQUIRES(!art::Locks::mutator_lock_) {
2368     barrier_.Increment(self_, t);
2369   }
2370 
2371  private:
2372   art::Thread* self_;
2373   bool is_running_;
2374   art::Barrier barrier_;
2375   art::Mutex release_mu_;
2376   art::Barrier release_barrier_;
2377   art::ConditionVariable release_cond_;
2378   std::atomic<uint32_t> count_;
2379   bool release_;
2380 };
2381 
2382 class ScopedSuspendClassLoading {
2383  public:
ScopedSuspendClassLoading(art::Thread * self,art::Runtime * runtime,RedefinitionDataHolder & h)2384   ScopedSuspendClassLoading(art::Thread* self, art::Runtime* runtime, RedefinitionDataHolder& h)
2385       REQUIRES_SHARED(art::Locks::mutator_lock_)
2386       : self_(self), runtime_(runtime), pauser_() {
2387     if (std::any_of(h.begin(), h.end(), [](auto r) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2388           return r.GetRedefinition().IsStructuralRedefinition();
2389         })) {
2390       VLOG(plugin) << "Pausing Class loading for structural redefinition.";
2391       pauser_.emplace(self);
2392       {
2393         art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
2394         uint32_t in_progress_defines = 0;
2395         {
2396           art::ScopedSuspendAll ssa(__FUNCTION__);
2397           pauser_->SetRunning();
2398           runtime_->GetRuntimeCallbacks()->AddClassLoadCallback(&pauser_.value());
2399           art::MutexLock mu(self_, *art::Locks::thread_list_lock_);
2400           runtime_->GetThreadList()->ForEach([&](art::Thread* t) {
2401             if (t != self_ && t->GetDefineClassCount() != 0) {
2402               in_progress_defines++;
2403             }
2404           });
2405           VLOG(plugin) << "Waiting for " << in_progress_defines
2406                        << " in progress class-loads to finish";
2407         }
2408         pauser_->WaitFor(in_progress_defines);
2409       }
2410     }
2411   }
~ScopedSuspendClassLoading()2412   ~ScopedSuspendClassLoading() {
2413     if (pauser_.has_value()) {
2414       art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
2415       art::ScopedSuspendAll ssa(__FUNCTION__);
2416       pauser_->Release();
2417       runtime_->GetRuntimeCallbacks()->RemoveClassLoadCallback(&pauser_.value());
2418     }
2419   }
2420 
2421  private:
2422   art::Thread* self_;
2423   art::Runtime* runtime_;
2424   std::optional<ClassDefinitionPauser> pauser_;
2425 };
2426 
2427 class ScopedSuspendAllocations {
2428  public:
ScopedSuspendAllocations(art::Runtime * runtime,RedefinitionDataHolder & h)2429   ScopedSuspendAllocations(art::Runtime* runtime, RedefinitionDataHolder& h)
2430       REQUIRES_SHARED(art::Locks::mutator_lock_)
2431       : paused_(false) {
2432     if (std::any_of(h.begin(),
2433                     h.end(),
2434                     [](auto r) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2435                       return r.GetRedefinition().IsStructuralRedefinition();
2436                     })) {
2437       VLOG(plugin) << "Pausing allocations for structural redefinition.";
2438       paused_ = true;
2439       AllocationManager::Get()->PauseAllocations(art::Thread::Current());
2440       // Collect garbage so we don't need to recreate as much.
2441       runtime->GetHeap()->CollectGarbage(/*clear_soft_references=*/false);
2442     }
2443   }
2444 
REQUIRES_SHARED(art::Locks::mutator_lock_)2445   ~ScopedSuspendAllocations() REQUIRES_SHARED(art::Locks::mutator_lock_) {
2446     if (paused_) {
2447       AllocationManager::Get()->ResumeAllocations(art::Thread::Current());
2448     }
2449   }
2450 
2451  private:
2452   bool paused_;
2453 
2454   DISALLOW_COPY_AND_ASSIGN(ScopedSuspendAllocations);
2455 };
2456 
Run()2457 jvmtiError Redefiner::Run() {
2458   art::StackHandleScope<1> hs(self_);
2459   // Sort the redefinitions_ array topologically by class. This makes later steps easier since we
2460   // know that every class precedes all of its supertypes.
2461   std::sort(redefinitions_.begin(),
2462             redefinitions_.end(),
2463             [&](auto& l, auto& r) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2464               return CompareClasses(l.GetMirrorClass(), r.GetMirrorClass());
2465             });
2466   // Allocate an array to hold onto all java temporary objects associated with this
2467   // redefinition. We will let this be collected after the end of this function.
2468   RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
2469   if (holder.IsNull()) {
2470     self_->AssertPendingOOMException();
2471     self_->ClearException();
2472     RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
2473     return result_;
2474   }
2475 
2476   // First we just allocate the ClassExt and its fields that we need. These can be updated
2477   // atomically without any issues (since we allocate the map arrays as empty).
2478   if (!CheckAllRedefinitionAreValid()) {
2479     return result_;
2480   }
2481   // Mark structural changes.
2482   MarkStructuralChanges(holder);
2483   // Now we pause class loading. If we are doing a structural redefinition we will need to get an
2484   // accurate picture of the classes loaded and having loads in the middle would make that
2485   // impossible. This only pauses class-loading if we actually have at least one structural
2486   // redefinition.
2487   ScopedSuspendClassLoading suspend_class_load(self_, runtime_, holder);
2488   if (!EnsureAllClassAllocationsFinished(holder) ||
2489       !FinishAllRemainingCommonAllocations(holder) ||
2490       !FinishAllNewClassAllocations(holder) ||
2491       !CheckAllClassesAreVerified(holder)) {
2492     return result_;
2493   }
2494 
2495   ScopedSuspendAllocations suspend_alloc(runtime_, holder);
2496   if (!CollectAndCreateNewInstances(holder)) {
2497     return result_;
2498   }
2499 
2500   // At this point we can no longer fail without corrupting the runtime state.
2501   for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2502     art::ClassLinker* cl = runtime_->GetClassLinker();
2503     if (data.GetSourceClassLoader() == nullptr) {
2504       // AppendToBootClassPath includes dex file registration.
2505       const art::DexFile& dex_file = data.GetRedefinition().GetDexFile();
2506       runtime_->AppendToBootClassPath(
2507           dex_file.GetLocation(), dex_file.GetLocation(), {{&dex_file, data.GetNewDexCache()}});
2508     } else {
2509       cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
2510     }
2511     DCHECK_EQ(cl->FindDexCache(self_, data.GetRedefinition().GetDexFile()), data.GetNewDexCache());
2512   }
2513   UnregisterAllBreakpoints();
2514 
2515   {
2516     // Disable GC and wait for it to be done if we are a moving GC.  This is fine since we are done
2517     // allocating so no deadlocks.
2518     ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
2519 
2520     // Do transition to final suspension
2521     // TODO We might want to give this its own suspended state!
2522     // TODO This isn't right. We need to change state without any chance of suspend ideally!
2523     art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
2524     art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend=*/true);
2525     for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2526       art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
2527       ClassRedefinition& redef = data.GetRedefinition();
2528       if (data.GetSourceClassLoader() != nullptr) {
2529         ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
2530       }
2531       redef.UpdateClass(data);
2532     }
2533     RestoreObsoleteMethodMapsIfUnneeded(holder);
2534     // TODO We should check for if any of the redefined methods are intrinsic methods here and, if
2535     // any are, force a full-world deoptimization before finishing redefinition. If we don't do this
2536     // then methods that have been jitted prior to the current redefinition being applied might
2537     // continue to use the old versions of the intrinsics!
2538     // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
2539     // owns the DexFile and when ownership is transferred.
2540     ReleaseAllDexFiles();
2541   }
2542   return OK;
2543 }
2544 
UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,const art::dex::ClassDef & class_def)2545 void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
2546                                                  const art::dex::ClassDef& class_def) {
2547   art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
2548   art::PointerSize image_pointer_size = linker->GetImagePointerSize();
2549   const art::dex::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
2550   const art::DexFile& old_dex_file = mclass->GetDexFile();
2551   // Update methods.
2552   for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
2553     // Reinitialize the method by calling `CopyFrom`. This ensures for example
2554     // the entrypoint and the hotness are reset.
2555     method.CopyFrom(&method, image_pointer_size);
2556     const art::dex::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
2557     art::dex::TypeIndex method_return_idx =
2558         dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptorView()));
2559     const auto* old_type_list = method.GetParameterTypeList();
2560     std::vector<art::dex::TypeIndex> new_type_list;
2561     for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
2562       new_type_list.push_back(
2563           dex_file_->GetIndexForTypeId(
2564               *dex_file_->FindTypeId(
2565                   old_dex_file.GetTypeDescriptorView(
2566                       old_dex_file.GetTypeId(
2567                           old_type_list->GetTypeItem(i).type_idx_)))));
2568     }
2569     const art::dex::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx, new_type_list);
2570     CHECK(proto_id != nullptr || old_type_list == nullptr);
2571     const art::dex::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
2572                                                                   *new_name_id,
2573                                                                   *proto_id);
2574     CHECK(method_id != nullptr);
2575     uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
2576     method.SetDexMethodIndex(dex_method_idx);
2577     driver_->runtime_->GetInstrumentation()->InitializeMethodsCode(&method, /*aot_code=*/ nullptr);
2578     if (method.HasCodeItem()) {
2579       method.SetCodeItem(
2580           dex_file_->GetCodeItem(dex_file_->FindCodeItemOffset(class_def, dex_method_idx)),
2581           dex_file_->IsCompactDexFile());
2582     }
2583     // Clear all the intrinsics related flags.
2584     method.SetNotIntrinsic();
2585   }
2586 }
2587 
UpdateFields(art::ObjPtr<art::mirror::Class> mclass)2588 void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
2589   // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
2590   for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
2591     for (art::ArtField& field : fields_iter) {
2592       const art::dex::TypeId* new_declaring_id =
2593           dex_file_->FindTypeId(field.GetDeclaringClassDescriptorView());
2594       const art::dex::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
2595       const art::dex::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptorView());
2596       CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
2597       const art::dex::FieldId* new_field_id =
2598           dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
2599       CHECK(new_field_id != nullptr);
2600       uint32_t new_field_index = dex_file_->GetIndexForFieldId(*new_field_id);
2601       // We only need to update the index since the other data in the ArtField cannot be updated.
2602       field.SetDexFieldIndex(new_field_index);
2603     }
2604   }
2605 }
2606 
CollectNewFieldAndMethodMappings(const RedefinitionDataIter & data,std::map<art::ArtMethod *,art::ArtMethod * > * method_map,std::map<art::ArtField *,art::ArtField * > * field_map)2607 void Redefiner::ClassRedefinition::CollectNewFieldAndMethodMappings(
2608     const RedefinitionDataIter& data,
2609     std::map<art::ArtMethod*, art::ArtMethod*>* method_map,
2610     std::map<art::ArtField*, art::ArtField*>* field_map) {
2611   for (auto [new_cls, old_cls] :
2612        art::ZipLeft(data.GetNewClasses()->Iterate(), data.GetOldClasses()->Iterate())) {
2613     for (art::ArtField& f : old_cls->GetSFields()) {
2614       (*field_map)[&f] = new_cls->FindDeclaredStaticField(f.GetName(), f.GetTypeDescriptor());
2615     }
2616     for (art::ArtField& f : old_cls->GetIFields()) {
2617       (*field_map)[&f] = new_cls->FindDeclaredInstanceField(f.GetName(), f.GetTypeDescriptor());
2618     }
2619     auto new_methods = new_cls->GetMethods(art::kRuntimePointerSize);
2620     for (art::ArtMethod& m : old_cls->GetMethods(art::kRuntimePointerSize)) {
2621       // No support for finding methods in this way since it's generally not needed. Just do it the
2622       // easy way.
2623       auto nm_iter = std::find_if(
2624           new_methods.begin(),
2625           new_methods.end(),
2626           [&](art::ArtMethod& cand) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2627             return cand.GetNameView() == m.GetNameView() && cand.GetSignature() == m.GetSignature();
2628           });
2629       CHECK(nm_iter != new_methods.end())
2630           << "Could not find redefined version of " << m.PrettyMethod();
2631       (*method_map)[&m] = &(*nm_iter);
2632     }
2633   }
2634 }
2635 
CopyField(art::ObjPtr<art::mirror::Object> target,art::ArtField * new_field,art::ObjPtr<art::mirror::Object> source,art::ArtField & old_field)2636 static void CopyField(art::ObjPtr<art::mirror::Object> target,
2637                       art::ArtField* new_field,
2638                       art::ObjPtr<art::mirror::Object> source,
2639                       art::ArtField& old_field) REQUIRES(art::Locks::mutator_lock_) {
2640   art::Primitive::Type ftype = old_field.GetTypeAsPrimitiveType();
2641   CHECK_EQ(ftype, new_field->GetTypeAsPrimitiveType())
2642       << old_field.PrettyField() << " vs " << new_field->PrettyField();
2643   if (ftype == art::Primitive::kPrimNot) {
2644     new_field->SetObject<false>(target, old_field.GetObject(source));
2645   } else {
2646     switch (ftype) {
2647 #define UPDATE_FIELD(TYPE)                                            \
2648   case art::Primitive::kPrim##TYPE:                                   \
2649     new_field->Set##TYPE<false>(target, old_field.Get##TYPE(source)); \
2650     break
2651       UPDATE_FIELD(Int);
2652       UPDATE_FIELD(Float);
2653       UPDATE_FIELD(Long);
2654       UPDATE_FIELD(Double);
2655       UPDATE_FIELD(Short);
2656       UPDATE_FIELD(Char);
2657       UPDATE_FIELD(Byte);
2658       UPDATE_FIELD(Boolean);
2659       case art::Primitive::kPrimNot:
2660       case art::Primitive::kPrimVoid:
2661         LOG(FATAL) << "Unexpected field with type " << ftype << " found!";
2662         UNREACHABLE();
2663 #undef UPDATE_FIELD
2664     }
2665   }
2666 }
2667 
CopyFields(bool is_static,art::ObjPtr<art::mirror::Object> target,art::ObjPtr<art::mirror::Class> target_class,art::ObjPtr<art::mirror::Object> source,art::ObjPtr<art::mirror::Class> source_class)2668 static void CopyFields(bool is_static,
2669                        art::ObjPtr<art::mirror::Object> target,
2670                        art::ObjPtr<art::mirror::Class> target_class,
2671                        art::ObjPtr<art::mirror::Object> source,
2672                        art::ObjPtr<art::mirror::Class> source_class)
2673     REQUIRES(art::Locks::mutator_lock_) {
2674   DCHECK(!source_class->IsObjectClass() && !target_class->IsObjectClass())
2675       << "Should not be overriding object class fields. Target: " << target_class->PrettyClass()
2676       << " Source: " << source_class->PrettyClass();
2677   for (art::ArtField& f : (is_static ? source_class->GetSFields() : source_class->GetIFields())) {
2678     art::ArtField* new_field =
2679         (is_static ? target_class->FindDeclaredStaticField(f.GetName(), f.GetTypeDescriptor())
2680                    : target_class->FindDeclaredInstanceField(f.GetName(), f.GetTypeDescriptor()));
2681     CHECK(new_field != nullptr) << "could not find new version of " << f.PrettyField();
2682     CopyField(target, new_field, source, f);
2683   }
2684   if (!is_static && !target_class->GetSuperClass()->IsObjectClass()) {
2685     CopyFields(
2686         is_static, target, target_class->GetSuperClass(), source, source_class->GetSuperClass());
2687   }
2688 }
2689 
ClearField(art::ObjPtr<art::mirror::Object> target,art::ArtField & field)2690 static void ClearField(art::ObjPtr<art::mirror::Object> target, art::ArtField& field)
2691     REQUIRES(art::Locks::mutator_lock_) {
2692   art::Primitive::Type ftype = field.GetTypeAsPrimitiveType();
2693   if (ftype == art::Primitive::kPrimNot) {
2694     field.SetObject<false>(target, nullptr);
2695   } else {
2696     switch (ftype) {
2697 #define UPDATE_FIELD(TYPE)             \
2698   case art::Primitive::kPrim##TYPE:    \
2699     field.Set##TYPE<false>(target, 0); \
2700     break
2701       UPDATE_FIELD(Int);
2702       UPDATE_FIELD(Float);
2703       UPDATE_FIELD(Long);
2704       UPDATE_FIELD(Double);
2705       UPDATE_FIELD(Short);
2706       UPDATE_FIELD(Char);
2707       UPDATE_FIELD(Byte);
2708       UPDATE_FIELD(Boolean);
2709       case art::Primitive::kPrimNot:
2710       case art::Primitive::kPrimVoid:
2711         LOG(FATAL) << "Unexpected field with type " << ftype << " found!";
2712         UNREACHABLE();
2713 #undef UPDATE_FIELD
2714     }
2715   }
2716 }
2717 
ClearFields(bool is_static,art::ObjPtr<art::mirror::Object> target,art::ObjPtr<art::mirror::Class> target_class)2718 static void ClearFields(bool is_static,
2719                         art::ObjPtr<art::mirror::Object> target,
2720                         art::ObjPtr<art::mirror::Class> target_class)
2721     REQUIRES(art::Locks::mutator_lock_) {
2722   DCHECK(!target_class->IsObjectClass());
2723   for (art::ArtField& f : (is_static ? target_class->GetSFields() : target_class->GetIFields())) {
2724     ClearField(target, f);
2725   }
2726   if (!is_static && !target_class->GetSuperClass()->IsObjectClass()) {
2727     ClearFields(is_static, target, target_class->GetSuperClass());
2728   }
2729 }
2730 
CopyAndClearFields(bool is_static,art::ObjPtr<art::mirror::Object> target,art::ObjPtr<art::mirror::Class> target_class,art::ObjPtr<art::mirror::Object> source,art::ObjPtr<art::mirror::Class> source_class)2731 static void CopyAndClearFields(bool is_static,
2732                                art::ObjPtr<art::mirror::Object> target,
2733                                art::ObjPtr<art::mirror::Class> target_class,
2734                                art::ObjPtr<art::mirror::Object> source,
2735                                art::ObjPtr<art::mirror::Class> source_class)
2736     REQUIRES(art::Locks::mutator_lock_) {
2737   // Copy all non-j.l.Object fields
2738   CopyFields(is_static, target, target_class, source, source_class);
2739   // Copy the lock-word.
2740   target->SetLockWord(source->GetLockWord(false), false);
2741   // Clear (reset) the old one.
2742   source->SetLockWord(art::LockWord::Default(), false);
2743   art::WriteBarrier::ForEveryFieldWrite(target);
2744 
2745   // Clear the fields from the old class. We don't need it anymore.
2746   ClearFields(is_static, source, source_class);
2747   art::WriteBarrier::ForEveryFieldWrite(source);
2748 }
2749 
UpdateClassStructurally(const RedefinitionDataIter & holder)2750 void Redefiner::ClassRedefinition::UpdateClassStructurally(const RedefinitionDataIter& holder) {
2751   DCHECK(holder.IsActuallyStructural());
2752   DCHECK(holder.IsInitialStructural());
2753   // LETS GO. We've got all new class structures so no need to do all the updating of the stacks.
2754   // Instead we need to update everything else.
2755   // Just replace the class and be done with it.
2756   art::Locks::mutator_lock_->AssertExclusiveHeld(driver_->self_);
2757   art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
2758   art::ScopedAssertNoThreadSuspension sants(__FUNCTION__);
2759   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> new_classes(holder.GetNewClasses());
2760   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> old_classes(holder.GetOldClasses());
2761   // Collect mappings from old to new fields/methods
2762   std::map<art::ArtMethod*, art::ArtMethod*> method_map;
2763   std::map<art::ArtField*, art::ArtField*> field_map;
2764   CollectNewFieldAndMethodMappings(holder, &method_map, &field_map);
2765   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> new_instances(
2766       holder.GetNewInstanceObjects());
2767   art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> old_instances(
2768       holder.GetOldInstanceObjects());
2769   // Once we do the ReplaceReferences old_classes will have the new_classes in it. We want to keep
2770   // ahold of the old classes so copy them now.
2771   std::vector<art::ObjPtr<art::mirror::Class>> old_classes_vec(old_classes->Iterate().begin(),
2772                                                                old_classes->Iterate().end());
2773   // Copy over the static fields of the class and all the instance fields.
2774   for (auto [new_class, old_class] : art::ZipLeft(new_classes->Iterate(), old_classes->Iterate())) {
2775     CHECK(!new_class.IsNull());
2776     CHECK(!old_class.IsNull());
2777     CHECK(!old_class->IsErroneous());
2778     if (old_class->GetStatus() > new_class->GetStatus()) {
2779       // Some verification/initialization step happened during interval between
2780       // creating the new class and now. Just copy the new status.
2781       new_class->SetStatusLocked(old_class->GetStatus());
2782     }
2783     CopyAndClearFields(true, new_class, new_class, old_class, old_class);
2784   }
2785 
2786   // Copy and clear the fields of the old-instances.
2787   for (auto [new_instance, old_instance] :
2788        art::ZipLeft(new_instances->Iterate(), old_instances->Iterate())) {
2789     CopyAndClearFields(/*is_static=*/false,
2790                        new_instance,
2791                        new_instance->GetClass(),
2792                        old_instance,
2793                        old_instance->GetClass());
2794   }
2795   // Mark old class and methods obsolete. Copy over any native implementation as well.
2796   for (auto [old_class, new_class] : art::ZipLeft(old_classes->Iterate(), new_classes->Iterate())) {
2797     old_class->SetObsoleteObject();
2798     // Mark methods obsolete and copy native implementation. We need to wait
2799     // until later to actually clear the jit data. We copy the native
2800     // implementation here since we don't want to race with any threads doing
2801     // RegisterNatives.
2802     for (art::ArtMethod& m : old_class->GetMethods(art::kRuntimePointerSize)) {
2803       if (m.IsNative()) {
2804         art::ArtMethod* new_method =
2805             new_class->FindClassMethod(m.GetNameView(), m.GetSignature(), art::kRuntimePointerSize);
2806         DCHECK(new_class->GetMethodsSlice(art::kRuntimePointerSize).Contains(new_method))
2807             << "Could not find method " << m.PrettyMethod() << " declared in new class!";
2808         DCHECK(new_method->IsNative());
2809         new_method->SetEntryPointFromJni(m.GetEntryPointFromJni());
2810       }
2811       m.SetIsObsolete();
2812       cl->SetEntryPointsForObsoleteMethod(&m);
2813       if (m.IsInvokable()) {
2814         m.SetDontCompile();
2815       }
2816     }
2817   }
2818   // Update live pointers in ART code.
2819   auto could_change_resolution_of = [&](auto* field_or_method,
2820                                         const auto& info) REQUIRES(art::Locks::mutator_lock_) {
2821     constexpr bool is_method = std::is_same_v<art::ArtMethod*, decltype(field_or_method)>;
2822     static_assert(is_method || std::is_same_v<art::ArtField*, decltype(field_or_method)>,
2823                   "Input is not field or method!");
2824     // Only dex-cache is used for resolution
2825     if (LIKELY(info.GetType() != art::ReflectionSourceType::kSourceDexCacheResolvedField &&
2826                info.GetType() != art::ReflectionSourceType::kSourceDexCacheResolvedMethod)) {
2827       return false;
2828     }
2829     if constexpr (is_method) {
2830       // Only direct methods are used without further indirection through a vtable/IFTable.
2831       // Constructors cannot be shadowed.
2832       if (LIKELY(!field_or_method->IsDirect() || field_or_method->IsConstructor())) {
2833         return false;
2834       }
2835     } else {
2836       // Only non-private fields can be shadowed in a manner that's visible.
2837       if (LIKELY(field_or_method->IsPrivate())) {
2838         return false;
2839       }
2840     }
2841     // We can only shadow things from our superclasses
2842     auto orig_classes_iter = old_classes->Iterate();
2843     auto replacement_classes_iter = new_classes->Iterate();
2844     art::ObjPtr<art::mirror::Class> f_or_m_class = field_or_method->GetDeclaringClass();
2845     if (LIKELY(!f_or_m_class->IsAssignableFrom(holder.GetMirrorClass()) &&
2846                std::find(orig_classes_iter.begin(), orig_classes_iter.end(), f_or_m_class) ==
2847                    orig_classes_iter.end())) {
2848       return false;
2849     }
2850     if constexpr (is_method) {
2851       return std::any_of(
2852           replacement_classes_iter.begin(),
2853           replacement_classes_iter.end(),
2854           [&](art::ObjPtr<art::mirror::Class> cand) REQUIRES(art::Locks::mutator_lock_) {
2855             auto direct_methods = cand->GetDirectMethods(art::kRuntimePointerSize);
2856             return std::find_if(direct_methods.begin(),
2857                                 direct_methods.end(),
2858                                 [&](art::ArtMethod& m) REQUIRES(art::Locks::mutator_lock_) {
2859                                   return UNLIKELY(m.HasSameNameAndSignature(field_or_method));
2860                                 }) != direct_methods.end();
2861           });
2862     } else {
2863       auto pred = [&](art::ArtField& f) REQUIRES(art::Locks::mutator_lock_) {
2864         return std::string_view(f.GetName()) == std::string_view(field_or_method->GetName()) &&
2865                std::string_view(f.GetTypeDescriptor()) ==
2866                    std::string_view(field_or_method->GetTypeDescriptor());
2867       };
2868       if (field_or_method->IsStatic()) {
2869         return std::any_of(
2870             replacement_classes_iter.begin(),
2871             replacement_classes_iter.end(),
2872             [&](art::ObjPtr<art::mirror::Class> cand) REQUIRES(art::Locks::mutator_lock_) {
2873               auto sfields = cand->GetSFields();
2874               return std::find_if(sfields.begin(), sfields.end(), pred) != sfields.end();
2875             });
2876       } else {
2877         return std::any_of(
2878             replacement_classes_iter.begin(),
2879             replacement_classes_iter.end(),
2880             [&](art::ObjPtr<art::mirror::Class> cand) REQUIRES(art::Locks::mutator_lock_) {
2881               auto ifields = cand->GetIFields();
2882               return std::find_if(ifields.begin(), ifields.end(), pred) != ifields.end();
2883             });
2884       }
2885     }
2886   };
2887   // TODO Performing 2 stack-walks back to back isn't the greatest. We might want to try to combine
2888   // it with the one ReplaceReferences does. Doing so would be rather complicated though.
2889   driver_->runtime_->VisitReflectiveTargets(
2890       [&](art::ArtField* f, const auto& info) REQUIRES(art::Locks::mutator_lock_) {
2891         DCHECK(f != nullptr) << info;
2892         auto it = field_map.find(f);
2893         if (UNLIKELY(could_change_resolution_of(f, info))) {
2894           // Dex-cache Resolution might change. Just clear the resolved value.
2895           VLOG(plugin) << "Clearing resolution " << info << " for (field) " << f->PrettyField();
2896           return static_cast<art::ArtField*>(nullptr);
2897         } else if (it != field_map.end()) {
2898           VLOG(plugin) << "Updating " << info << " object for (field) "
2899                        << it->second->PrettyField();
2900           return it->second;
2901         }
2902         return f;
2903       },
2904       [&](art::ArtMethod* m, const auto& info) REQUIRES(art::Locks::mutator_lock_) {
2905         DCHECK(m != nullptr) << info;
2906         auto it = method_map.find(m);
2907         if (UNLIKELY(could_change_resolution_of(m, info))) {
2908           // Dex-cache Resolution might change. Just clear the resolved value.
2909           VLOG(plugin) << "Clearing resolution " << info << " for (method) " << m->PrettyMethod();
2910           return static_cast<art::ArtMethod*>(nullptr);
2911         } else if (it != method_map.end()) {
2912           VLOG(plugin) << "Updating " << info << " object for (method) "
2913                       << it->second->PrettyMethod();
2914           return it->second;
2915         }
2916         return m;
2917       });
2918 
2919   // Force every frame of every thread to deoptimize (any frame might have eg offsets compiled in).
2920   driver_->runtime_->GetInstrumentation()->DeoptimizeAllThreadFrames();
2921 
2922   std::unordered_map<art::ObjPtr<art::mirror::Object>,
2923                      art::ObjPtr<art::mirror::Object>,
2924                      art::HashObjPtr> map;
2925   for (auto [new_class, old_class] : art::ZipLeft(new_classes->Iterate(), old_classes->Iterate())) {
2926     map.emplace(old_class, new_class);
2927   }
2928   for (auto [new_instance, old_instance] :
2929        art::ZipLeft(new_instances->Iterate(), old_instances->Iterate())) {
2930     map.emplace(old_instance, new_instance);
2931     // Bare-bones check that the mapping is correct.
2932     CHECK(new_instance->GetClass() == map[old_instance->GetClass()]->AsClass())
2933         << new_instance->GetClass()->PrettyClass() << " vs "
2934         << map[old_instance->GetClass()]->AsClass()->PrettyClass();
2935   }
2936 
2937   // Actually perform the general replacement. This doesn't affect ArtMethod/ArtFields. It does
2938   // affect the declaring_class field of all the obsolete objects, which is unfortunate and needs to
2939   // be undone. This replaces the mirror::Class in 'holder' as well. It's magic!
2940   HeapExtensions::ReplaceReferences(driver_->self_, map);
2941 
2942   // Undo the replacement of old_class with new_class for the methods / fields on the old_class.
2943   // It is hard to ensure that we don't replace the declaring class of the old class field / methods
2944   // isn't impacted by ReplaceReferences. It is just simpler to undo the replacement here.
2945   std::for_each(
2946       old_classes_vec.cbegin(),
2947       old_classes_vec.cend(),
2948       [](art::ObjPtr<art::mirror::Class> orig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2949         orig->VisitMethods(
2950             [&](art::ArtMethod* method) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2951               if (method->IsCopied()) {
2952                 // Copied methods have interfaces as their declaring class.
2953                 return;
2954               }
2955               method->SetDeclaringClass(orig);
2956             },
2957             art::kRuntimePointerSize);
2958         orig->VisitFields([&](art::ArtField* field) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2959           field->SetDeclaringClass(orig);
2960         });
2961       });
2962 
2963   // Save the old class so that the JIT gc doesn't get confused by it being collected before the
2964   // jit code. This is also needed to keep the dex-caches of any obsolete methods live.
2965   for (auto [new_class, old_class] :
2966        art::ZipLeft(new_classes->Iterate(), art::MakeIterationRange(old_classes_vec))) {
2967     new_class->GetExtData()->SetObsoleteClass(old_class);
2968   }
2969 
2970   art::jit::Jit* jit = driver_->runtime_->GetJit();
2971   if (jit != nullptr) {
2972     // Clear jit.
2973     // TODO We might want to have some way to tell the JIT not to wait the kJitSamplesBatchSize
2974     // invokes to start compiling things again.
2975     jit->GetCodeCache()->InvalidateAllCompiledCode();
2976   }
2977 
2978   // Clear thread caches
2979   {
2980     // TODO We might be able to avoid doing this but given the rather unstructured nature of the
2981     // interpreter cache it's probably not worth the effort.
2982     art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
2983     driver_->runtime_->GetThreadList()->ForEach(
2984         [](art::Thread* t) { t->GetInterpreterCache()->Clear(t); });
2985   }
2986 
2987   if (art::kIsDebugBuild) {
2988     // Just make sure we didn't screw up any of the now obsolete methods or fields. We need their
2989     // declaring-class to still be the obolete class
2990     std::for_each(
2991         old_classes_vec.cbegin(),
2992         old_classes_vec.cend(),
2993         [](art::ObjPtr<art::mirror::Class> orig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2994           orig->VisitMethods(
2995               [&](art::ArtMethod* method) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2996                 if (method->IsCopied()) {
2997                   // Copied methods have interfaces as their declaring class.
2998                   return;
2999                 }
3000                 DCHECK_EQ(method->GetDeclaringClass(), orig)
3001                     << method->GetDeclaringClass()->PrettyClass() << " vs " << orig->PrettyClass();
3002               },
3003               art::kRuntimePointerSize);
3004           orig->VisitFields([&](art::ArtField* field) REQUIRES_SHARED(art::Locks::mutator_lock_) {
3005             DCHECK_EQ(field->GetDeclaringClass(), orig)
3006                 << field->GetDeclaringClass()->PrettyClass() << " vs " << orig->PrettyClass();
3007           });
3008         });
3009   }
3010 }
3011 
3012 // Redefines the class in place
UpdateClassInPlace(const RedefinitionDataIter & holder)3013 void Redefiner::ClassRedefinition::UpdateClassInPlace(const RedefinitionDataIter& holder) {
3014   art::ObjPtr<art::mirror::Class> mclass(holder.GetMirrorClass());
3015   // TODO Rewrite so we don't do a stack walk for each and every class.
3016   FindAndAllocateObsoleteMethods(mclass);
3017   art::ObjPtr<art::mirror::DexCache> new_dex_cache(holder.GetNewDexCache());
3018   art::ObjPtr<art::mirror::Object> original_dex_file(holder.GetOriginalDexFile());
3019   DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
3020   const art::dex::ClassDef& class_def = dex_file_->GetClassDef(0);
3021   UpdateMethods(mclass, class_def);
3022   UpdateFields(mclass);
3023 
3024   art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
3025   CHECK(!ext.IsNull());
3026   ext->SetOriginalDexFile(original_dex_file);
3027 
3028   // If this is the first time the class is being redefined, store
3029   // the native DexFile pointer and initial ClassDef index in ClassExt.
3030   // This preserves the pointer for hiddenapi access checks which need
3031   // to read access flags from the initial DexFile.
3032   if (ext->GetPreRedefineDexFile() == nullptr) {
3033     ext->SetPreRedefineDexFile(&mclass->GetDexFile());
3034     ext->SetPreRedefineClassDefIndex(mclass->GetDexClassDefIndex());
3035   }
3036 
3037   // Update the class fields.
3038   // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
3039   // to call GetReturnTypeDescriptor and GetParameterTypeList above).
3040   mclass->SetDexCache(new_dex_cache.Ptr());
3041   mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
3042   mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
3043 
3044   // Notify the jit that all the methods in this class were redefined. Need to do this last since
3045   // the jit relies on the dex_file_ being correct (for native methods at least) to find the method
3046   // meta-data.
3047   art::jit::Jit* jit = driver_->runtime_->GetJit();
3048   if (jit != nullptr) {
3049     art::PointerSize image_pointer_size =
3050         driver_->runtime_->GetClassLinker()->GetImagePointerSize();
3051     auto code_cache = jit->GetCodeCache();
3052     // Non-invokable methods don't have any JIT data associated with them so we don't need to tell
3053     // the jit about them.
3054     for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
3055       if (method.IsInvokable()) {
3056         code_cache->NotifyMethodRedefined(&method);
3057       }
3058     }
3059   }
3060 }
3061 
3062 // Performs final updates to class for redefinition.
UpdateClass(const RedefinitionDataIter & holder)3063 void Redefiner::ClassRedefinition::UpdateClass(const RedefinitionDataIter& holder) {
3064   CHECK(holder.IsInitialized());
3065   if (holder.IsInitialStructural()) {
3066     UpdateClassStructurally(holder);
3067   } else if (!holder.IsActuallyStructural()) {
3068     UpdateClassInPlace(holder);
3069   }
3070 }
3071 
3072 // Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
3073 // obsolete methods).
RestoreObsoleteMethodMapsIfUnneeded(const RedefinitionDataIter * cur_data)3074 void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
3075     const RedefinitionDataIter* cur_data) {
3076   if (cur_data->IsActuallyStructural()) {
3077     // We didn't touch these in this case.
3078     return;
3079   }
3080   art::ObjPtr<art::mirror::Class> klass = GetMirrorClass();
3081   art::ObjPtr<art::mirror::ClassExt> ext = klass->GetExtData();
3082   art::ObjPtr<art::mirror::PointerArray> methods = ext->GetObsoleteMethods();
3083   art::ObjPtr<art::mirror::PointerArray> old_methods = cur_data->GetOldObsoleteMethods();
3084   int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
3085   int32_t expected_length =
3086       old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
3087   // Check to make sure we are only undoing this one.
3088   if (methods.IsNull()) {
3089     // No new obsolete methods! We can get rid of the maps.
3090     ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
3091   } else if (expected_length == methods->GetLength()) {
3092     for (int32_t i = 0; i < expected_length; i++) {
3093       art::ArtMethod* expected = nullptr;
3094       if (i < old_length) {
3095         expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
3096       }
3097       if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
3098         // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
3099         // obsolete methods array.
3100         return;
3101       }
3102     }
3103     // No new obsolete methods! We can get rid of the maps.
3104     ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
3105   }
3106 }
3107 
3108 // This function does all (java) allocations we need to do for the Class being redefined.
3109 // TODO Change this name maybe?
EnsureClassAllocationsFinished(RedefinitionDataIter * cur_data)3110 bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
3111     /*out*/RedefinitionDataIter* cur_data) {
3112   art::StackHandleScope<2> hs(driver_->self_);
3113   art::Handle<art::mirror::Class> klass(hs.NewHandle(
3114       driver_->self_->DecodeJObject(klass_)->AsClass()));
3115   if (klass == nullptr) {
3116     RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
3117     return false;
3118   }
3119   // Allocate the classExt
3120   art::Handle<art::mirror::ClassExt> ext =
3121       hs.NewHandle(art::mirror::Class::EnsureExtDataPresent(klass, driver_->self_));
3122   if (ext == nullptr) {
3123     // No memory. Clear exception (it's not useful) and return error.
3124     driver_->self_->AssertPendingOOMException();
3125     driver_->self_->ClearException();
3126     RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
3127     return false;
3128   }
3129   if (!cur_data->IsActuallyStructural()) {
3130     CHECK(!IsStructuralRedefinition());
3131     // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
3132     // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
3133     // are only modified when all threads (other than the modifying one) are suspended we don't need
3134     // to worry about missing the unsynchronized writes to the array. We do synchronize when setting
3135     // it however, since that can happen at any time.
3136     cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
3137     cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
3138     // FIXME: The `ClassExt::ExtendObsoleteArrays()` is non-atomic and does not ensure proper
3139     // memory visibility, so it can race with `ArtMethod::GetObsoleteDexCache()`.
3140     // We should allocate the new arrays here but record it in the redefinition data and set the
3141     // new arrays in `ClassExt` later with all other threads suspended.
3142     if (!art::mirror::ClassExt::ExtendObsoleteArrays(
3143             ext, driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
3144       // OOM. Clear exception and return error.
3145       driver_->self_->AssertPendingOOMException();
3146       driver_->self_->ClearException();
3147       RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
3148       return false;
3149     }
3150   }
3151   return true;
3152 }
3153 
3154 }  // namespace openjdkjvmti
3155