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