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