blob: 58c1c4e92608e27525cee01bed198d81c974b307 [file] [log] [blame]
Alex Lighta01de592016-11-15 10:43:06 -08001/* 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
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000034#include <algorithm>
35#include <atomic>
Alex Lighte7a33542019-04-10 14:22:49 -070036#include <iterator>
Alex Lighta01de592016-11-15 10:43:06 -080037#include <limits>
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000038#include <sstream>
Vladimir Markoeb37ba52019-02-05 14:10:38 +000039#include <string_view>
Alex Lighte7a33542019-04-10 14:22:49 -070040#include <unordered_map>
Alex Lighta01de592016-11-15 10:43:06 -080041
Andreas Gampe57943812017-12-06 21:39:13 -080042#include <android-base/logging.h>
43#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080044
Alex Light986914b2019-11-19 01:12:25 +000045#include "alloc_manager.h"
46#include "android-base/macros.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000047#include "android-base/thread_annotations.h"
Andreas Gampea1d2f952017-04-20 22:53:58 -070048#include "art_field-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000049#include "art_field.h"
Alex Lighta01de592016-11-15 10:43:06 -080050#include "art_jvmti.h"
Steven Morelande431e272017-07-18 16:53:49 -070051#include "art_method-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000052#include "art_method.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010053#include "base/array_ref.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000054#include "base/casts.h"
55#include "base/enums.h"
56#include "base/globals.h"
Alex Light270db1c2019-12-03 12:20:01 +000057#include "base/iteration_range.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000058#include "base/length_prefixed_array.h"
Alex Light270db1c2019-12-03 12:20:01 +000059#include "base/locks.h"
60#include "base/stl_util.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000061#include "base/utils.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080062#include "class_linker-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000063#include "class_linker.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010064#include "class_root-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000065#include "class_status.h"
Alex Light5643caf2017-02-08 11:39:07 -080066#include "debugger.h"
David Sehr013fd802018-01-11 22:55:24 -080067#include "dex/art_dex_file_loader.h"
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -070068#include "dex/class_accessor-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000069#include "dex/class_accessor.h"
David Sehr9e734c72018-01-04 17:56:19 -080070#include "dex/dex_file.h"
71#include "dex/dex_file_loader.h"
72#include "dex/dex_file_types.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000073#include "dex/primitive.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080074#include "dex/signature-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000075#include "dex/signature.h"
Alex Lighta01de592016-11-15 10:43:06 -080076#include "events-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000077#include "events.h"
Alex Lighta01de592016-11-15 10:43:06 -080078#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080079#include "gc/heap.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000080#include "gc/heap-inl.h"
81#include "gc/heap-visit-objects-inl.h"
82#include "handle.h"
83#include "handle_scope.h"
Alex Lighta01de592016-11-15 10:43:06 -080084#include "instrumentation.h"
Alex Light07f06212017-06-01 14:01:43 -070085#include "intern_table.h"
Alex Lightdba61482016-12-21 08:20:29 -080086#include "jit/jit.h"
87#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010088#include "jni/jni_env_ext-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000089#include "jni/jni_id_manager.h"
90#include "jvmti.h"
Alex Lighta01de592016-11-15 10:43:06 -080091#include "jvmti_allocator.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010092#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070093#include "mirror/array-alloc-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000094#include "mirror/array.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070095#include "mirror/class-alloc-inl.h"
Alex Light6161f132017-01-25 10:30:20 -080096#include "mirror/class-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +000097#include "mirror/class-refvisitor-inl.h"
98#include "mirror/class.h"
Vladimir Markobb206de2019-03-28 10:30:32 +000099#include "mirror/class_ext-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000100#include "mirror/dex_cache-inl.h"
101#include "mirror/dex_cache.h"
102#include "mirror/executable-inl.h"
103#include "mirror/field-inl.h"
Alex Light163652e2020-01-08 15:18:25 -0800104#include "mirror/field.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000105#include "mirror/method.h"
106#include "mirror/method_handle_impl-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -0800107#include "mirror/object.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -0700108#include "mirror/object_array-alloc-inl.h"
109#include "mirror/object_array-inl.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000110#include "mirror/object_array.h"
111#include "mirror/string.h"
Alex Lightc18eba32019-09-24 14:36:27 -0700112#include "mirror/var_handle.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -0700113#include "nativehelper/scoped_local_ref.h"
Alex Lighte77b48b2017-02-22 11:08:06 -0800114#include "non_debuggable_classes.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000115#include "obj_ptr.h"
Alex Lighta01de592016-11-15 10:43:06 -0800116#include "object_lock.h"
Alex Light24627892019-11-06 10:28:21 -0800117#include "reflective_value_visitor.h"
Alex Lighta01de592016-11-15 10:43:06 -0800118#include "runtime.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000119#include "runtime_globals.h"
Alex Light986914b2019-11-19 01:12:25 +0000120#include "scoped_thread_state_change.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +0100121#include "stack.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000122#include "thread.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +0100123#include "thread_list.h"
Alex Lighta26e3492017-06-27 17:55:37 -0700124#include "ti_breakpoint.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000125#include "ti_class_definition.h"
Alex Lighteb98b082017-01-25 13:02:32 -0800126#include "ti_class_loader.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000127#include "ti_heap.h"
128#include "ti_logging.h"
129#include "ti_thread.h"
Alex Light0e692732017-01-10 15:00:05 -0800130#include "transform.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -0700131#include "verifier/class_verifier.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -0700132#include "verifier/verifier_enums.h"
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000133#include "well_known_classes.h"
134#include "write_barrier.h"
Alex Lighta01de592016-11-15 10:43:06 -0800135
136namespace openjdkjvmti {
137
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000138// 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
140constexpr bool kCheckAllMethodsSeenOnce = art::kIsDebugBuild;
141
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800142using android::base::StringPrintf;
143
Alex Lighteee0bd42017-02-14 15:31:45 +0000144// 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.
147class ObsoleteMap {
148 public:
Alex Lighte7a33542019-04-10 14:22:49 -0700149 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original) const
Alex Lighteee0bd42017-02-14 15:31:45 +0000150 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);
Alex Lighteee0bd42017-02-14 15:31:45 +0000156 return res;
157 } else {
158 return nullptr;
159 }
160 }
161
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
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 }
Orion Hodsonaacf9772020-07-22 21:51:00 +0100189 // Check that the same slot in obsolete_dex_caches_ is free.
Alex Lighteee0bd42017-02-14 15:31:45 +0000190 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
191 }
192
Alex Lighte7a33542019-04-10 14:22:49 -0700193 struct ObsoleteMethodPair {
194 art::ArtMethod* old_method;
195 art::ArtMethod* obsolete_method;
196 };
197
Vladimir Markoeab02482019-05-09 10:28:17 +0100198 class ObsoleteMapIter {
Alex Lighte7a33542019-04-10 14:22:49 -0700199 public:
Vladimir Markoeab02482019-05-09 10:28:17 +0100200 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
Alex Lighte7a33542019-04-10 14:22:49 -0700206 ObsoleteMethodPair operator*() const
207 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
Vladimir Markoeab02482019-05-09 10:28:17 +0100208 art::ArtMethod* obsolete = map_->obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
209 iter_->second, art::kRuntimePointerSize);
Alex Lighte7a33542019-04-10 14:22:49 -0700210 DCHECK(obsolete != nullptr);
211 return { iter_->first, obsolete };
212 }
213
214 bool operator==(ObsoleteMapIter other) const {
215 return map_ == other.map_ && iter_ == other.iter_;
216 }
217
218 bool operator!=(ObsoleteMapIter other) const {
219 return !(*this == other);
220 }
221
Vladimir Markoeab02482019-05-09 10:28:17 +0100222 ObsoleteMapIter operator++(int) {
Alex Lighte7a33542019-04-10 14:22:49 -0700223 ObsoleteMapIter retval = *this;
224 ++(*this);
225 return retval;
226 }
227
Vladimir Markoeab02482019-05-09 10:28:17 +0100228 ObsoleteMapIter operator++() {
Alex Lighte7a33542019-04-10 14:22:49 -0700229 ++iter_;
230 return *this;
231 }
232
233 private:
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_;
Vladimir Markoeab02482019-05-09 10:28:17 +0100239 std::unordered_map<art::ArtMethod*, int32_t>::const_iterator iter_;
Alex Lighte7a33542019-04-10 14:22:49 -0700240
241 friend class ObsoleteMap;
242 };
243
244 ObsoleteMapIter end() const {
245 return ObsoleteMapIter(this, id_map_.cend());
246 }
247
248 ObsoleteMapIter begin() const {
249 return ObsoleteMapIter(this, id_map_.cbegin());
250 }
251
Alex Lighteee0bd42017-02-14 15:31:45 +0000252 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
Alex Lightdba61482016-12-21 08:20:29 -0800262// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
Orion Hodsonaacf9772020-07-22 21:51:00 +0100263// some basic soundness checks that the obsolete method is valid.
Alex Lightdba61482016-12-21 08:20:29 -0800264class ObsoleteMethodStackVisitor : public art::StackVisitor {
265 protected:
266 ObsoleteMethodStackVisitor(
267 art::Thread* thread,
268 art::LinearAlloc* allocator,
269 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000270 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800271 : StackVisitor(thread,
Andreas Gampe6e897762018-10-16 13:09:32 -0700272 /*context=*/nullptr,
Alex Lightdba61482016-12-21 08:20:29 -0800273 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
274 allocator_(allocator),
275 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800276 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800277
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100278 ~ObsoleteMethodStackVisitor() override {}
Alex Lightdba61482016-12-21 08:20:29 -0800279
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.
Alex Light007ada22017-01-10 13:33:56 -0800284 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800285 art::Thread* thread,
286 art::LinearAlloc* allocator,
287 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000288 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800289 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800290 ObsoleteMethodStackVisitor visitor(thread,
291 allocator,
292 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800293 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800294 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800295 }
296
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100297 bool VisitFrame() override REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000298 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800299 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800300 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800301 // We cannot ensure that the right dex file is used in inlined frames so we don't support
302 // redefining them.
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000303 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition: "
304 << old_method->PrettyMethod() << " is inlined into "
305 << GetOuterMethod()->PrettyMethod();
Alex Lighteee0bd42017-02-14 15:31:45 +0000306 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
307 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800308 // 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);
Alex Light5c11a792017-03-10 14:29:22 -0800313 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800314 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
315 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800316 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();
Alex Lightfcbafb32017-02-02 15:09:54 -0800320 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700321 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000322 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800323 }
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
Alex Lighteee0bd42017-02-14 15:31:45 +0000336 // 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_;
Alex Lightdba61482016-12-21 08:20:29 -0800339};
340
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000341template <RedefinitionType kType>
342jvmtiError
343Redefiner::IsModifiableClassGeneric(jvmtiEnv* env, jclass klass, jboolean* is_redefinable) {
344 if (env == nullptr) {
345 return ERR(INVALID_ENVIRONMENT);
346 }
Alex Lighte4a88632017-01-10 07:41:24 -0800347 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));
Alex Light413a8ad2019-02-14 10:19:44 -0800351 if (obj.IsNull() || !obj->IsClass()) {
Alex Lighte4a88632017-01-10 07:41:24 -0800352 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 =
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000357 Redefiner::GetClassRedefinitionError<kType>(h_klass, &err_unused) != ERR(UNMODIFIABLE_CLASS)
358 ? JNI_TRUE
359 : JNI_FALSE;
Alex Lighte4a88632017-01-10 07:41:24 -0800360 return OK;
361}
362
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000363jvmtiError
364Redefiner::IsStructurallyModifiableClass(jvmtiEnv* env, jclass klass, jboolean* is_redefinable) {
365 return Redefiner::IsModifiableClassGeneric<RedefinitionType::kStructural>(
366 env, klass, is_redefinable);
367}
368
369jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env, jclass klass, jboolean* is_redefinable) {
370 return Redefiner::IsModifiableClassGeneric<RedefinitionType::kNormal>(env, klass, is_redefinable);
371}
372
373template <RedefinitionType kType>
374jvmtiError Redefiner::GetClassRedefinitionError(jclass klass, /*out*/ std::string* error_msg) {
Alex Light9e7859c2018-04-05 13:49:43 -0700375 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));
Alex Light413a8ad2019-02-14 10:19:44 -0800379 if (obj.IsNull() || !obj->IsClass()) {
Alex Light9e7859c2018-04-05 13:49:43 -0700380 return ERR(INVALID_CLASS);
381 }
382 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
Alex Lightd55b8442019-10-15 15:46:07 -0700383 return Redefiner::GetClassRedefinitionError<kType>(h_klass, error_msg);
Alex Light9e7859c2018-04-05 13:49:43 -0700384}
385
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000386template <RedefinitionType kType>
Alex Lighte4a88632017-01-10 07:41:24 -0800387jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000388 /*out*/ std::string* error_msg) {
389 art::Thread* self = art::Thread::Current();
Alex Light9e7859c2018-04-05 13:49:43 -0700390 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.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000394 if (klass->GetLockOwnerThreadId() == self->GetThreadId()) {
Alex Light9e7859c2018-04-05 13:49:43 -0700395 *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 }
Alex Lighte4a88632017-01-10 07:41:24 -0800404 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);
Alex Light09f274f2017-02-21 15:00:48 -0800410 } else if (klass->IsStringClass()) {
411 *error_msg = "Modification of String class is not supported";
412 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800413 } 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
Alex Lighte77b48b2017-02-22 11:08:06 -0800421 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000422 if (klass.Get() == self->DecodeJObject(c)->AsClass()) {
Alex Lighte77b48b2017-02-22 11:08:06 -0800423 *error_msg = "Class might have stack frames that cannot be made obsolete";
424 return ERR(UNMODIFIABLE_CLASS);
425 }
426 }
427
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000428 if (kType == RedefinitionType::kStructural) {
Alex Lightfb119572019-09-18 15:04:53 -0700429 // 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 }
Alex Lightf1b18fa2019-11-11 14:22:00 -0800449 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);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000454 }
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 }
Alex Light3f0dca12020-01-27 17:20:28 -0800464 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);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000483 }
Alex Light3f0dca12020-01-27 17:20:28 -0800484 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;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000502 }
Alex Lighte4a88632017-01-10 07:41:24 -0800503 return OK;
504}
505
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000506template jvmtiError Redefiner::GetClassRedefinitionError<RedefinitionType::kNormal>(
507 art::Handle<art::mirror::Class> klass, /*out*/ std::string* error_msg);
508template jvmtiError Redefiner::GetClassRedefinitionError<RedefinitionType::kStructural>(
509 art::Handle<art::mirror::Class> klass, /*out*/ std::string* error_msg);
510
Alex Lighta01de592016-11-15 10:43:06 -0800511// Moves dex data to an anonymous, read-only mmap'd region.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100512art::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(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800516 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lightb7354d52017-03-30 15:17:01 -0700517 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800518 PROT_READ|PROT_WRITE,
Andreas Gampe6e897762018-10-16 13:09:32 -0700519 /*low_4gb=*/ false,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100520 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);
Alex Lighta01de592016-11-15 10:43:06 -0800526 }
Alex Lighta01de592016-11-15 10:43:06 -0800527 return map;
528}
529
Alex Lighta7e38d82017-01-19 14:57:28 -0800530Redefiner::ClassRedefinition::ClassRedefinition(
531 Redefiner* driver,
532 jclass klass,
533 const art::DexFile* redefined_dex_file,
534 const char* class_sig,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100535 art::ArrayRef<const unsigned char> orig_dex_file) :
Alex Lighta7e38d82017-01-19 14:57:28 -0800536 driver_(driver),
537 klass_(klass),
538 dex_file_(redefined_dex_file),
539 class_sig_(class_sig),
540 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800541 GetMirrorClass()->MonitorEnter(driver_->self_);
542}
543
544Redefiner::ClassRedefinition::~ClassRedefinition() {
545 if (driver_ != nullptr) {
546 GetMirrorClass()->MonitorExit(driver_->self_);
547 }
548}
549
Alex Lightd55b8442019-10-15 15:46:07 -0700550template<RedefinitionType kType>
551jvmtiError Redefiner::RedefineClassesGeneric(jvmtiEnv* jenv,
552 jint class_count,
553 const jvmtiClassDefinition* definitions) {
Alex Light3732beb2019-10-04 13:35:34 -0700554 art::Runtime* runtime = art::Runtime::Current();
555 art::Thread* self = art::Thread::Current();
556 ArtJvmTiEnv* env = ArtJvmTiEnv::AsArtJvmTiEnv(jenv);
Alex Light0e692732017-01-10 15:00:05 -0800557 if (env == nullptr) {
Alex Light3732beb2019-10-04 13:35:34 -0700558 JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE env was null!";
Alex Light0e692732017-01-10 15:00:05 -0800559 return ERR(INVALID_ENVIRONMENT);
560 } else if (class_count < 0) {
Alex Light3732beb2019-10-04 13:35:34 -0700561 JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE class_count was less then 0";
Alex Light0e692732017-01-10 15:00:05 -0800562 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) {
Alex Light3732beb2019-10-04 13:35:34 -0700567 JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE null definitions!";
Alex Light0e692732017-01-10 15:00:05 -0800568 return ERR(NULL_POINTER);
569 }
Alex Light3732beb2019-10-04 13:35:34 -0700570 std::string error_msg;
Alex Light6ac57502017-01-19 15:05:06 -0800571 std::vector<ArtClassDefinition> def_vector;
572 def_vector.reserve(class_count);
573 for (jint i = 0; i < class_count; i++) {
Alex Lightd55b8442019-10-15 15:46:07 -0700574 jvmtiError res = Redefiner::GetClassRedefinitionError<RedefinitionType::kNormal>(
575 definitions[i].klass, &error_msg);
Alex Lightce6ee702017-03-06 15:46:43 -0800576 if (res != OK) {
Alex Light3732beb2019-10-04 13:35:34 -0700577 JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE " << error_msg;
Alex Lightce6ee702017-03-06 15:46:43 -0800578 return res;
Alex Lightce6ee702017-03-06 15:46:43 -0800579 }
Alex Light6ac57502017-01-19 15:05:06 -0800580 ArtClassDefinition def;
Alex Light64e4c142018-01-30 13:46:37 -0800581 res = def.Init(self, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800582 if (res != OK) {
Alex Light3732beb2019-10-04 13:35:34 -0700583 JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE bad definition " << i;
Alex Light6ac57502017-01-19 15:05:06 -0800584 return res;
585 }
586 def_vector.push_back(std::move(def));
587 }
588 // Call all the transformation events.
Alex Lightd55b8442019-10-15 15:46:07 -0700589 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);
Alex Light3732beb2019-10-04 13:35:34 -0700594 if (res != OK) {
595 JVMTI_LOG(WARNING, env) << "FAILURE TO REDEFINE " << error_msg;
596 }
597 return res;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000598}
599
Alex Lightd55b8442019-10-15 15:46:07 -0700600jvmtiError 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
612jvmtiError Redefiner::RedefineClasses(jvmtiEnv* jenv,
613 jint class_count,
614 const jvmtiClassDefinition* definitions) {
615 return RedefineClassesGeneric<RedefinitionType::kNormal>(jenv, class_count, definitions);
616}
617
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000618jvmtiError 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;
Alex Light6ac57502017-01-19 15:05:06 -0800648}
649
650jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
651 art::Runtime* runtime,
652 art::Thread* self,
653 const std::vector<ArtClassDefinition>& definitions,
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000654 RedefinitionType type,
Alex Light6ac57502017-01-19 15:05:06 -0800655 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 }
Alex Lightc2d0c962019-10-23 14:14:25 -0700661 // 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
Alex Light0e692732017-01-10 15:00:05 -0800666 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
667 // are going to redefine.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000668 // TODO We should prevent user-code suspensions to make sure this isn't held for too long.
Alex Light0e692732017-01-10 15:00:05 -0800669 art::jit::ScopedJitSuspend suspend_jit;
670 // Get shared mutator lock so we can lock all the classes.
671 art::ScopedObjectAccess soa(self);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000672 Redefiner r(env, runtime, self, type, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800673 for (const ArtClassDefinition& def : definitions) {
674 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700675 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800676 jvmtiError res = r.AddRedefinition(env, def);
677 if (res != OK) {
678 return res;
679 }
Alex Light0e692732017-01-10 15:00:05 -0800680 }
681 }
682 return r.Run();
683}
684
Alex Light6ac57502017-01-19 15:05:06 -0800685jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800686 std::string original_dex_location;
687 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700688 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800689 *error_msg_ = "Unable to get original dex file location!";
690 return ret;
691 }
Alex Light52a2db52017-01-19 23:00:21 +0000692 char* generic_ptr_unused = nullptr;
693 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700694 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800695 *error_msg_ = "Unable to get class signature!";
696 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000697 }
Andreas Gampe54711412017-02-21 12:41:43 -0800698 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
699 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100700 art::MemMap map = MoveDataToMemMap(original_dex_location, def.GetDexData(), error_msg_);
Alex Light6ac57502017-01-19 15:05:06 -0800701 std::ostringstream os;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100702 if (!map.IsValid()) {
Alex Lightb7354d52017-03-30 15:17:01 -0700703 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800704 << "in dex file " << original_dex_location << " because: " << *error_msg_;
705 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800706 return ERR(OUT_OF_MEMORY);
707 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100708 if (map.Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800709 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800710 return ERR(INVALID_CLASS_FORMAT);
711 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100712 std::string name = map.GetName();
713 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
David Sehr013fd802018-01-11 22:55:24 -0800714 const art::ArtDexFileLoader dex_file_loader;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100715 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(name,
David Sehr013fd802018-01-11 22:55:24 -0800716 checksum,
717 std::move(map),
Andreas Gampe6e897762018-10-16 13:09:32 -0700718 /*verify=*/true,
719 /*verify_checksum=*/true,
David Sehr013fd802018-01-11 22:55:24 -0800720 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800721 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700722 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800723 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800724 return ERR(INVALID_CLASS_FORMAT);
725 }
Alex Light0e692732017-01-10 15:00:05 -0800726 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800727 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700728 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800729 dex_file.release(),
730 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700731 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800732 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800733}
734
Vladimir Marko4617d582019-03-28 13:48:31 +0000735art::ObjPtr<art::mirror::Class> Redefiner::ClassRedefinition::GetMirrorClass() {
Alex Light0e692732017-01-10 15:00:05 -0800736 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800737}
738
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000739art::ObjPtr<art::mirror::ClassLoader> Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800740 return GetMirrorClass()->GetClassLoader();
741}
742
Alex Light0e692732017-01-10 15:00:05 -0800743art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
744 art::Handle<art::mirror::ClassLoader> loader) {
Alex Light07f06212017-06-01 14:01:43 -0700745 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(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100749 art::GetClassRoot<art::mirror::DexCache>(cl)->AllocObject(driver_->self_))));
Alex Light07f06212017-06-01 14:01:43 -0700750 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_);
David Srbecky86d6cd52020-12-02 18:13:10 +0000761 cache->SetLocation(location.Get());
762 cache->InitializeNativeFields(dex_file_.get(),
763 loader.IsNull() ? driver_->runtime_->GetLinearAlloc()
764 : loader->GetAllocator());
Alex Light07f06212017-06-01 14:01:43 -0700765 return cache.Get();
Alex Lighta01de592016-11-15 10:43:06 -0800766}
767
Alex Light0e692732017-01-10 15:00:05 -0800768void Redefiner::RecordFailure(jvmtiError result,
769 const std::string& class_sig,
770 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800771 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800772 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800773 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800774 result_ = result;
775}
776
Alex Light2f814aa2017-03-24 15:21:34 +0000777art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800778 // If we have been specifically given a new set of bytes use that
779 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800780 return art::mirror::ByteArray::AllocateAndFill(
781 driver_->self_,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100782 reinterpret_cast<const signed char*>(original_dex_file_.data()),
Vladimir Markobcf17522018-06-01 13:14:32 +0100783 original_dex_file_.size()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800784 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800785
786 // See if we already have one set.
787 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
788 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000789 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
790 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800791 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000792 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800793 }
Alex Lighta01de592016-11-15 10:43:06 -0800794 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800795
Alex Light2f814aa2017-03-24 15:21:34 +0000796 // return the current dex_cache which has the dex file in it.
797 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800798 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000799 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800800 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
801 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800802 }
Alex Light2f814aa2017-03-24 15:21:34 +0000803 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800804}
805
Alex Lightdba61482016-12-21 08:20:29 -0800806struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000807 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800808 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800809 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800810
Alex Lighteee0bd42017-02-14 15:31:45 +0000811 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
812 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800813};
814
Alex Lightdba61482016-12-21 08:20:29 -0800815void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
816 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800817 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
818 data->allocator,
819 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000820 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800821}
822
823// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
824// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800825// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
Vladimir Markod93e3742018-07-18 10:58:13 +0100826void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(
827 art::ObjPtr<art::mirror::Class> art_klass) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000828 DCHECK(!IsStructuralRedefinition());
Alex Lightdba61482016-12-21 08:20:29 -0800829 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
Vladimir Markod93e3742018-07-18 10:58:13 +0100830 art::ObjPtr<art::mirror::ClassExt> ext = art_klass->GetExtData();
Alex Lightdba61482016-12-21 08:20:29 -0800831 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800832 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000833 // This holds pointers to the obsolete methods map fields which are updated as needed.
834 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
835 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800836 // Add all the declared methods to the map
837 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800838 if (m.IsIntrinsic()) {
839 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
840 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
841 << "methods that have already been compiled.";
842 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000843 // It is possible to simply filter out some methods where they cannot really become obsolete,
844 // such as native methods and keep their original (possibly optimized) implementations. We don't
845 // do this, however, since we would need to mark these functions (still in the classes
846 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
847 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
848 // error checking from the interpreter which ensure we don't try to start executing obsolete
849 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000850 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800851 }
852 {
Alex Light0e692732017-01-10 15:00:05 -0800853 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800854 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
855 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Vladimir Markoeab02482019-05-09 10:28:17 +0100856 // After we've done walking all threads' stacks and updating method pointers on them,
857 // update JIT data structures (used by the stack walk above) to point to the new methods.
Alex Lighte7a33542019-04-10 14:22:49 -0700858 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
859 if (jit != nullptr) {
860 for (const ObsoleteMap::ObsoleteMethodPair& it : *ctx.obsolete_map) {
861 // Notify the JIT we are making this obsolete method. It will update the jit's internal
862 // structures to keep track of the new obsolete method.
863 jit->GetCodeCache()->MoveObsoleteMethod(it.old_method, it.obsolete_method);
864 }
865 }
Alex Lightdba61482016-12-21 08:20:29 -0800866 }
Alex Lightdba61482016-12-21 08:20:29 -0800867}
868
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000869namespace {
870template <typename T> struct SignatureType {};
871template <> struct SignatureType<art::ArtField> { using type = std::string_view; };
872template <> struct SignatureType<art::ArtMethod> { using type = art::Signature; };
873
874template <typename T> struct NameAndSignature {
875 public:
876 using SigType = typename SignatureType<T>::type;
877
878 NameAndSignature(const art::DexFile* dex_file, uint32_t id);
879
880 NameAndSignature(const std::string_view& name, const SigType& sig) : name_(name), sig_(sig) {}
881
882 bool operator==(const NameAndSignature<T>& o) {
883 return name_ == o.name_ && sig_ == o.sig_;
Alex Light6161f132017-01-25 10:30:20 -0800884 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000885
886 std::ostream& dump(std::ostream& os) const {
887 return os << "'" << name_ << "' (sig: " << sig_ << ")";
888 }
889
890 std::string ToString() const {
891 std::ostringstream os;
892 os << *this;
893 return os.str();
894 }
895
896 std::string_view name_;
897 SigType sig_;
898};
899
900template <typename T>
901std::ostream& operator<<(std::ostream& os, const NameAndSignature<T>& nas) {
902 return nas.dump(os);
Alex Light6161f132017-01-25 10:30:20 -0800903}
904
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000905using FieldNameAndSignature = NameAndSignature<art::ArtField>;
906template <>
907FieldNameAndSignature::NameAndSignature(const art::DexFile* dex_file, uint32_t id)
908 : FieldNameAndSignature(dex_file->GetFieldName(dex_file->GetFieldId(id)),
909 dex_file->GetFieldTypeDescriptor(dex_file->GetFieldId(id))) {}
910
911using MethodNameAndSignature = NameAndSignature<art::ArtMethod>;
912template <>
913MethodNameAndSignature::NameAndSignature(const art::DexFile* dex_file, uint32_t id)
914 : MethodNameAndSignature(dex_file->GetMethodName(dex_file->GetMethodId(id)),
915 dex_file->GetMethodSignature(dex_file->GetMethodId(id))) {}
916
917} // namespace
918
919void Redefiner::ClassRedefinition::RecordNewMethodAdded() {
920 DCHECK(driver_->IsStructuralRedefinition());
921 added_methods_ = true;
922}
923void Redefiner::ClassRedefinition::RecordNewFieldAdded() {
924 DCHECK(driver_->IsStructuralRedefinition());
925 added_fields_ = true;
926}
927
928bool Redefiner::ClassRedefinition::CheckMethods() {
Alex Light6161f132017-01-25 10:30:20 -0800929 art::StackHandleScope<1> hs(driver_->self_);
930 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
931 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
932
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000933 // Make sure we have the same number of methods (or the same or greater if we're structural).
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700934 art::ClassAccessor accessor(*dex_file_, dex_file_->GetClassDef(0));
935 uint32_t num_new_method = accessor.NumMethods();
Alex Light6161f132017-01-25 10:30:20 -0800936 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000937 const bool is_structural = driver_->IsStructuralRedefinition();
938 if (!is_structural && num_new_method != num_old_method) {
Alex Light6161f132017-01-25 10:30:20 -0800939 bool bigger = num_new_method > num_old_method;
940 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
941 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
942 StringPrintf("Total number of declared methods changed from %d to %d",
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000943 num_old_method,
944 num_new_method));
Alex Light6161f132017-01-25 10:30:20 -0800945 return false;
946 }
947
948 // Skip all of the fields. We should have already checked this.
Alex Light6161f132017-01-25 10:30:20 -0800949 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
950 // files have the same number of methods, which means there must be an equal amount of additions
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700951 // and removals. We should have already checked the fields.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000952 const art::DexFile& old_dex_file = h_klass->GetDexFile();
953 art::ClassAccessor old_accessor(old_dex_file, *h_klass->GetClassDef());
954 // We need this to check for methods going missing in structural cases.
955 std::vector<bool> seen_old_methods(
956 (kCheckAllMethodsSeenOnce || is_structural) ? old_accessor.NumMethods() : 0, false);
957 const auto old_methods = old_accessor.GetMethods();
958 for (const art::ClassAccessor::Method& new_method : accessor.GetMethods()) {
Alex Light6161f132017-01-25 10:30:20 -0800959 // Get the data on the method we are searching for
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000960 MethodNameAndSignature new_method_id(dex_file_.get(), new_method.GetIndex());
961 const auto old_iter =
962 std::find_if(old_methods.cbegin(), old_methods.cend(), [&](const auto& current_old_method) {
963 MethodNameAndSignature old_method_id(&old_dex_file, current_old_method.GetIndex());
964 return old_method_id == new_method_id;
965 });
966
Alex Light986914b2019-11-19 01:12:25 +0000967 if (!new_method.IsStaticOrDirect()) {
968 RecordHasVirtualMembers();
969 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000970 if (old_iter == old_methods.cend()) {
Alex Light270db1c2019-12-03 12:20:01 +0000971 if (is_structural) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000972 RecordNewMethodAdded();
973 } else {
974 RecordFailure(
975 ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
976 StringPrintf("Unknown virtual method %s was added!", new_method_id.ToString().c_str()));
977 return false;
978 }
979 } else if (new_method.GetAccessFlags() != old_iter->GetAccessFlags()) {
980 RecordFailure(
981 ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
982 StringPrintf("method %s had different access flags", new_method_id.ToString().c_str()));
Alex Light6161f132017-01-25 10:30:20 -0800983 return false;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000984 } else if (kCheckAllMethodsSeenOnce || is_structural) {
985 // We only need this if we are structural.
986 size_t off = std::distance(old_methods.cbegin(), old_iter);
987 DCHECK(!seen_old_methods[off])
988 << "field at " << off << "("
989 << MethodNameAndSignature(&old_dex_file, old_iter->GetIndex()) << ") already seen?";
990 seen_old_methods[off] = true;
Alex Light6161f132017-01-25 10:30:20 -0800991 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +0000992 }
993 if ((kCheckAllMethodsSeenOnce || is_structural) &&
994 !std::all_of(seen_old_methods.cbegin(), seen_old_methods.cend(), [](auto x) { return x; })) {
995 DCHECK(is_structural) << "We should have hit an earlier failure before getting here!";
996 auto first_fail =
997 std::find_if(seen_old_methods.cbegin(), seen_old_methods.cend(), [](auto x) { return !x; });
998 auto off = std::distance(seen_old_methods.cbegin(), first_fail);
999 auto fail = old_methods.cbegin();
1000 std::advance(fail, off);
1001 RecordFailure(
1002 ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
1003 StringPrintf("Method %s missing!",
Alex Lightdaad67f2019-12-16 13:01:46 -08001004 MethodNameAndSignature(&old_dex_file, fail->GetIndex()).ToString().c_str()));
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001005 return false;
Alex Light6161f132017-01-25 10:30:20 -08001006 }
1007 return true;
1008}
1009
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001010bool Redefiner::ClassRedefinition::CheckFields() {
Alex Light6161f132017-01-25 10:30:20 -08001011 art::StackHandleScope<1> hs(driver_->self_);
1012 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
1013 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001014 art::ClassAccessor new_accessor(*dex_file_, dex_file_->GetClassDef(0));
1015
Alex Light6161f132017-01-25 10:30:20 -08001016 const art::DexFile& old_dex_file = h_klass->GetDexFile();
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001017 art::ClassAccessor old_accessor(old_dex_file, *h_klass->GetClassDef());
Alex Light6161f132017-01-25 10:30:20 -08001018 // Instance and static fields can be differentiated by their flags so no need to check them
1019 // separately.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001020 std::vector<bool> seen_old_fields(old_accessor.NumFields(), false);
1021 const auto old_fields = old_accessor.GetFields();
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -07001022 for (const art::ClassAccessor::Field& new_field : new_accessor.GetFields()) {
Alex Light6161f132017-01-25 10:30:20 -08001023 // Get the data on the method we are searching for
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001024 FieldNameAndSignature new_field_id(dex_file_.get(), new_field.GetIndex());
1025 const auto old_iter =
1026 std::find_if(old_fields.cbegin(), old_fields.cend(), [&](const auto& old_iter) {
1027 FieldNameAndSignature old_field_id(&old_dex_file, old_iter.GetIndex());
1028 return old_field_id == new_field_id;
1029 });
Alex Light986914b2019-11-19 01:12:25 +00001030 if (!new_field.IsStatic()) {
1031 RecordHasVirtualMembers();
1032 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001033 if (old_iter == old_fields.cend()) {
Alex Light270db1c2019-12-03 12:20:01 +00001034 if (driver_->IsStructuralRedefinition()) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001035 RecordNewFieldAdded();
1036 } else {
1037 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
1038 StringPrintf("Unknown field %s added!", new_field_id.ToString().c_str()));
1039 return false;
1040 }
1041 } else if (new_field.GetAccessFlags() != old_iter->GetAccessFlags()) {
1042 RecordFailure(
1043 ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
1044 StringPrintf("Field %s had different access flags", new_field_id.ToString().c_str()));
Alex Light6161f132017-01-25 10:30:20 -08001045 return false;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001046 } else {
1047 size_t off = std::distance(old_fields.cbegin(), old_iter);
1048 DCHECK(!seen_old_fields[off])
1049 << "field at " << off << "(" << FieldNameAndSignature(&old_dex_file, old_iter->GetIndex())
1050 << ") already seen?";
1051 seen_old_fields[off] = true;
Alex Light6161f132017-01-25 10:30:20 -08001052 }
Alex Light6161f132017-01-25 10:30:20 -08001053 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001054 if (!std::all_of(seen_old_fields.cbegin(), seen_old_fields.cend(), [](auto x) { return x; })) {
1055 auto first_fail =
1056 std::find_if(seen_old_fields.cbegin(), seen_old_fields.cend(), [](auto x) { return !x; });
1057 auto off = std::distance(seen_old_fields.cbegin(), first_fail);
1058 auto fail = old_fields.cbegin();
1059 std::advance(fail, off);
1060 RecordFailure(
1061 ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
1062 StringPrintf("Field %s is missing!",
1063 FieldNameAndSignature(&old_dex_file, fail->GetIndex()).ToString().c_str()));
Alex Light6161f132017-01-25 10:30:20 -08001064 return false;
1065 }
1066 return true;
1067}
1068
Alex Light0e692732017-01-10 15:00:05 -08001069bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -08001070 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +00001071 // Easy check that only 1 class def is present.
1072 if (dex_file_->NumClassDefs() != 1) {
1073 RecordFailure(ERR(ILLEGAL_ARGUMENT),
1074 StringPrintf("Expected 1 class def in dex file but found %d",
1075 dex_file_->NumClassDefs()));
1076 return false;
1077 }
1078 // Get the ClassDef from the new DexFile.
1079 // Since the dex file has only a single class def the index is always 0.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001080 const art::dex::ClassDef& def = dex_file_->GetClassDef(0);
Alex Light460d1b42017-01-10 15:37:17 +00001081 // Get the class as it is now.
1082 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
1083
1084 // Check the access flags didn't change.
1085 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
1086 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
1087 "Cannot change modifiers of class by redefinition");
1088 return false;
1089 }
1090
1091 // Check class name.
1092 // These should have been checked by the dexfile verifier on load.
1093 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
1094 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
1095 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
1096 if (!current_class->DescriptorEquals(descriptor)) {
1097 std::string storage;
1098 RecordFailure(ERR(NAMES_DONT_MATCH),
1099 StringPrintf("expected file to contain class called '%s' but found '%s'!",
1100 current_class->GetDescriptor(&storage),
1101 descriptor));
1102 return false;
1103 }
1104 if (current_class->IsObjectClass()) {
1105 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
1106 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
1107 return false;
1108 }
1109 } else {
1110 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
1111 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
1112 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
1113 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
1114 return false;
1115 }
1116 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001117 const art::dex::TypeList* interfaces = dex_file_->GetInterfacesList(def);
Alex Light460d1b42017-01-10 15:37:17 +00001118 if (interfaces == nullptr) {
1119 if (current_class->NumDirectInterfaces() != 0) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001120 // TODO Support this for kStructural.
Alex Light460d1b42017-01-10 15:37:17 +00001121 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
1122 return false;
1123 }
1124 } else {
1125 DCHECK(!current_class->IsProxyClass());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001126 const art::dex::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
Alex Light460d1b42017-01-10 15:37:17 +00001127 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001128 // TODO Support this for kStructural.
Alex Light460d1b42017-01-10 15:37:17 +00001129 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
1130 return false;
1131 }
1132 // The order of interfaces is (barely) meaningful so we error if it changes.
1133 const art::DexFile& orig_dex_file = current_class->GetDexFile();
1134 for (uint32_t i = 0; i < interfaces->Size(); i++) {
1135 if (strcmp(
1136 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
1137 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
1138 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
1139 "Interfaces changed or re-ordered");
1140 return false;
1141 }
1142 }
1143 }
Alex Light460d1b42017-01-10 15:37:17 +00001144 return true;
1145}
1146
Alex Light0e692732017-01-10 15:00:05 -08001147bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -08001148 std::string err;
Alex Light0e692732017-01-10 15:00:05 -08001149 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +00001150
Alex Lighte4a88632017-01-10 07:41:24 -08001151 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001152 jvmtiError res;
Alex Lightd55b8442019-10-15 15:46:07 -07001153 if (driver_->type_ == RedefinitionType::kStructural && this->IsStructuralRedefinition()) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001154 res = Redefiner::GetClassRedefinitionError<RedefinitionType::kStructural>(h_klass, &err);
Alex Lightd55b8442019-10-15 15:46:07 -07001155 } else {
1156 res = Redefiner::GetClassRedefinitionError<RedefinitionType::kNormal>(h_klass, &err);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001157 }
Alex Lighte4a88632017-01-10 07:41:24 -08001158 if (res != OK) {
1159 RecordFailure(res, err);
1160 return false;
1161 } else {
1162 return true;
1163 }
Alex Light460d1b42017-01-10 15:37:17 +00001164}
1165
Alex Light0e692732017-01-10 15:00:05 -08001166bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Lightd55b8442019-10-15 15:46:07 -07001167 return CheckClass() && CheckFields() && CheckMethods() && CheckRedefinable();
Alex Light460d1b42017-01-10 15:37:17 +00001168}
1169
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001170class RedefinitionDataIter;
1171
Alex Light0e692732017-01-10 15:00:05 -08001172// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
Orion Hodsonaacf9772020-07-22 21:51:00 +01001173// reasonable way. This adds no fields to the normal ObjectArray. By doing this we can avoid
Alex Light0e692732017-01-10 15:00:05 -08001174// having to deal with the fact that we need to hold an arbitrary number of references live.
1175class RedefinitionDataHolder {
1176 public:
1177 enum DataSlot : int32_t {
1178 kSlotSourceClassLoader = 0,
1179 kSlotJavaDexFile = 1,
1180 kSlotNewDexFileCookie = 2,
1181 kSlotNewDexCache = 3,
1182 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -08001183 kSlotOrigDexFile = 5,
Alex Light1e3926a2017-04-07 10:38:06 -07001184 kSlotOldObsoleteMethods = 6,
1185 kSlotOldDexCaches = 7,
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001186 kSlotNewClassObject = 8,
Alex Light986914b2019-11-19 01:12:25 +00001187 kSlotOldInstanceObjects = 9,
1188 kSlotNewInstanceObjects = 10,
Alex Light270db1c2019-12-03 12:20:01 +00001189 kSlotOldClasses = 11,
1190 kSlotNewClasses = 12,
Alex Light0e692732017-01-10 15:00:05 -08001191
1192 // Must be last one.
Alex Light270db1c2019-12-03 12:20:01 +00001193 kNumSlots = 13,
Alex Light0e692732017-01-10 15:00:05 -08001194 };
1195
1196 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
1197 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
1198 // the passed in handle-scope.
1199 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
1200 art::Runtime* runtime,
1201 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001202 std::vector<Redefiner::ClassRedefinition>* redefinitions)
1203 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001204 arr_(hs->NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
1205 self,
1206 art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Object>>(runtime->GetClassLinker()),
1207 redefinitions->size() * kNumSlots))),
Alex Lightfb537082019-12-10 14:38:34 -08001208 redefinitions_(redefinitions),
1209 initialized_(redefinitions_->size(), false),
1210 actually_structural_(redefinitions_->size(), false),
1211 initial_structural_(redefinitions_->size(), false) {}
Alex Light0e692732017-01-10 15:00:05 -08001212
1213 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1214 return arr_.IsNull();
1215 }
1216
Vladimir Markod93e3742018-07-18 10:58:13 +01001217 art::ObjPtr<art::mirror::ClassLoader> GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -08001218 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +01001219 return art::ObjPtr<art::mirror::ClassLoader>::DownCast(
1220 GetSlot(klass_index, kSlotSourceClassLoader));
Alex Light0e692732017-01-10 15:00:05 -08001221 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001222 art::ObjPtr<art::mirror::Object> GetJavaDexFile(jint klass_index) const
Alex Light8c889d22017-02-06 13:58:27 -08001223 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -08001224 return GetSlot(klass_index, kSlotJavaDexFile);
1225 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001226 art::ObjPtr<art::mirror::LongArray> GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -08001227 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +01001228 return art::ObjPtr<art::mirror::LongArray>::DownCast(
1229 GetSlot(klass_index, kSlotNewDexFileCookie));
Alex Light0e692732017-01-10 15:00:05 -08001230 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001231 art::ObjPtr<art::mirror::DexCache> GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -08001232 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +01001233 return art::ObjPtr<art::mirror::DexCache>::DownCast(GetSlot(klass_index, kSlotNewDexCache));
Alex Light0e692732017-01-10 15:00:05 -08001234 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001235 art::ObjPtr<art::mirror::Class> GetMirrorClass(jint klass_index) const
Alex Light8c889d22017-02-06 13:58:27 -08001236 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +01001237 return art::ObjPtr<art::mirror::Class>::DownCast(GetSlot(klass_index, kSlotMirrorClass));
Alex Light0e692732017-01-10 15:00:05 -08001238 }
1239
Vladimir Markod93e3742018-07-18 10:58:13 +01001240 art::ObjPtr<art::mirror::Object> GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -08001241 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +01001242 return art::ObjPtr<art::mirror::Object>::DownCast(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -08001243 }
1244
Vladimir Markod93e3742018-07-18 10:58:13 +01001245 art::ObjPtr<art::mirror::PointerArray> GetOldObsoleteMethods(jint klass_index) const
Alex Light1e3926a2017-04-07 10:38:06 -07001246 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +01001247 return art::ObjPtr<art::mirror::PointerArray>::DownCast(
Alex Light1e3926a2017-04-07 10:38:06 -07001248 GetSlot(klass_index, kSlotOldObsoleteMethods));
1249 }
1250
Vladimir Markod93e3742018-07-18 10:58:13 +01001251 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> GetOldDexCaches(
1252 jint klass_index) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1253 return art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>>::DownCast(
Alex Light1e3926a2017-04-07 10:38:06 -07001254 GetSlot(klass_index, kSlotOldDexCaches));
1255 }
1256
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001257 art::ObjPtr<art::mirror::Class> GetNewClassObject(jint klass_index) const
1258 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1259 return art::ObjPtr<art::mirror::Class>::DownCast(GetSlot(klass_index, kSlotNewClassObject));
1260 }
1261
Alex Light986914b2019-11-19 01:12:25 +00001262 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> GetOldInstanceObjects(
1263 jint klass_index) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1264 return art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>>::DownCast(
1265 GetSlot(klass_index, kSlotOldInstanceObjects));
1266 }
1267
1268 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> GetNewInstanceObjects(
1269 jint klass_index) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1270 return art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>>::DownCast(
1271 GetSlot(klass_index, kSlotNewInstanceObjects));
1272 }
Alex Light270db1c2019-12-03 12:20:01 +00001273 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> GetOldClasses(jint klass_index) const
1274 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1275 return art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>>::DownCast(
1276 GetSlot(klass_index, kSlotOldClasses));
1277 }
1278 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> GetNewClasses(jint klass_index) const
1279 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1280 return art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>>::DownCast(
1281 GetSlot(klass_index, kSlotNewClasses));
1282 }
Alex Lightfb537082019-12-10 14:38:34 -08001283 bool IsInitialized(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1284 return initialized_[klass_index];
1285 }
1286 bool IsActuallyStructural(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1287 return actually_structural_[klass_index];
1288 }
1289
1290 bool IsInitialStructural(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1291 return initial_structural_[klass_index];
1292 }
Alex Light986914b2019-11-19 01:12:25 +00001293
Vladimir Markod93e3742018-07-18 10:58:13 +01001294 void SetSourceClassLoader(jint klass_index, art::ObjPtr<art::mirror::ClassLoader> loader)
Alex Light0e692732017-01-10 15:00:05 -08001295 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1296 SetSlot(klass_index, kSlotSourceClassLoader, loader);
1297 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001298 void SetJavaDexFile(jint klass_index, art::ObjPtr<art::mirror::Object> dexfile)
Alex Light0e692732017-01-10 15:00:05 -08001299 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1300 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
1301 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001302 void SetNewDexFileCookie(jint klass_index, art::ObjPtr<art::mirror::LongArray> cookie)
Alex Light0e692732017-01-10 15:00:05 -08001303 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1304 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
1305 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001306 void SetNewDexCache(jint klass_index, art::ObjPtr<art::mirror::DexCache> cache)
Alex Light0e692732017-01-10 15:00:05 -08001307 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1308 SetSlot(klass_index, kSlotNewDexCache, cache);
1309 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001310 void SetMirrorClass(jint klass_index, art::ObjPtr<art::mirror::Class> klass)
Alex Light0e692732017-01-10 15:00:05 -08001311 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1312 SetSlot(klass_index, kSlotMirrorClass, klass);
1313 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001314 void SetOriginalDexFile(jint klass_index, art::ObjPtr<art::mirror::Object> bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -08001315 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1316 SetSlot(klass_index, kSlotOrigDexFile, bytes);
1317 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001318 void SetOldObsoleteMethods(jint klass_index, art::ObjPtr<art::mirror::PointerArray> methods)
Alex Light1e3926a2017-04-07 10:38:06 -07001319 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1320 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
1321 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001322 void SetOldDexCaches(jint klass_index,
1323 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)
Alex Light1e3926a2017-04-07 10:38:06 -07001324 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1325 SetSlot(klass_index, kSlotOldDexCaches, caches);
1326 }
Alex Light0e692732017-01-10 15:00:05 -08001327
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001328 void SetNewClassObject(jint klass_index, art::ObjPtr<art::mirror::Class> klass)
1329 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1330 SetSlot(klass_index, kSlotNewClassObject, klass);
1331 }
1332
Alex Light986914b2019-11-19 01:12:25 +00001333 void SetOldInstanceObjects(jint klass_index,
1334 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)
1335 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1336 SetSlot(klass_index, kSlotOldInstanceObjects, objs);
1337 }
1338 void SetNewInstanceObjects(jint klass_index,
1339 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)
1340 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1341 SetSlot(klass_index, kSlotNewInstanceObjects, objs);
1342 }
Alex Light270db1c2019-12-03 12:20:01 +00001343 void SetOldClasses(jint klass_index,
1344 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)
1345 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1346 SetSlot(klass_index, kSlotOldClasses, klasses);
1347 }
1348 void SetNewClasses(jint klass_index,
1349 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)
1350 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1351 SetSlot(klass_index, kSlotNewClasses, klasses);
1352 }
Alex Lightfb537082019-12-10 14:38:34 -08001353 void SetInitialized(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1354 initialized_[klass_index] = true;
1355 }
1356 void SetActuallyStructural(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1357 actually_structural_[klass_index] = true;
1358 }
1359 void SetInitialStructural(jint klass_index) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1360 initial_structural_[klass_index] = true;
1361 }
Alex Light8c889d22017-02-06 13:58:27 -08001362 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -08001363 return arr_->GetLength() / kNumSlots;
1364 }
1365
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001366 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
1367 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1368 return redefinitions_;
1369 }
1370
1371 bool operator==(const RedefinitionDataHolder& other) const
1372 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1373 return arr_.Get() == other.arr_.Get();
1374 }
1375
1376 bool operator!=(const RedefinitionDataHolder& other) const
1377 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1378 return !(*this == other);
1379 }
1380
1381 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
1382 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
1383
Alex Light0e692732017-01-10 15:00:05 -08001384 private:
Alex Light8c889d22017-02-06 13:58:27 -08001385 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001386 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Lightfb537082019-12-10 14:38:34 -08001387 // Used to mark a particular redefinition as fully initialized.
1388 std::vector<bool> initialized_;
1389 // Used to mark a redefinition as 'actually' structural. That is either the redefinition is
1390 // structural or a superclass is.
1391 std::vector<bool> actually_structural_;
1392 // Used to mark a redefinition as the initial structural redefinition. This redefinition will take
1393 // care of updating all of its subtypes.
1394 std::vector<bool> initial_structural_;
Alex Light0e692732017-01-10 15:00:05 -08001395
Vladimir Markod93e3742018-07-18 10:58:13 +01001396 art::ObjPtr<art::mirror::Object> GetSlot(jint klass_index, DataSlot slot) const
1397 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -08001398 DCHECK_LT(klass_index, Length());
1399 return arr_->Get((kNumSlots * klass_index) + slot);
1400 }
1401
1402 void SetSlot(jint klass_index,
1403 DataSlot slot,
1404 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1405 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
1406 DCHECK_LT(klass_index, Length());
1407 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
1408 }
1409
1410 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
1411};
1412
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001413class RedefinitionDataIter {
1414 public:
1415 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
1416
1417 RedefinitionDataIter(const RedefinitionDataIter&) = default;
1418 RedefinitionDataIter(RedefinitionDataIter&&) = default;
1419 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
1420 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
1421
1422 bool operator==(const RedefinitionDataIter& other) const
1423 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1424 return idx_ == other.idx_ && holder_ == other.holder_;
1425 }
1426
1427 bool operator!=(const RedefinitionDataIter& other) const
1428 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1429 return !(*this == other);
1430 }
1431
1432 RedefinitionDataIter operator++() { // Value after modification.
1433 idx_++;
1434 return *this;
1435 }
1436
1437 RedefinitionDataIter operator++(int) {
1438 RedefinitionDataIter temp = *this;
1439 idx_++;
1440 return temp;
1441 }
1442
1443 RedefinitionDataIter operator+(ssize_t delta) const {
1444 RedefinitionDataIter temp = *this;
1445 temp += delta;
1446 return temp;
1447 }
1448
1449 RedefinitionDataIter& operator+=(ssize_t delta) {
1450 idx_ += delta;
1451 return *this;
1452 }
1453
Alex Light986914b2019-11-19 01:12:25 +00001454 // Compat for STL iterators.
1455 RedefinitionDataIter& operator*() {
1456 return *this;
1457 }
1458
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001459 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1460 return (*holder_.GetRedefinitions())[idx_];
1461 }
1462
1463 RedefinitionDataHolder& GetHolder() {
1464 return holder_;
1465 }
1466
Vladimir Markod93e3742018-07-18 10:58:13 +01001467 art::ObjPtr<art::mirror::ClassLoader> GetSourceClassLoader() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001468 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1469 return holder_.GetSourceClassLoader(idx_);
1470 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001471 art::ObjPtr<art::mirror::Object> GetJavaDexFile() const
1472 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001473 return holder_.GetJavaDexFile(idx_);
1474 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001475 art::ObjPtr<art::mirror::LongArray> GetNewDexFileCookie() const
1476 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001477 return holder_.GetNewDexFileCookie(idx_);
1478 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001479 art::ObjPtr<art::mirror::DexCache> GetNewDexCache() const
1480 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001481 return holder_.GetNewDexCache(idx_);
1482 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001483 art::ObjPtr<art::mirror::Class> GetMirrorClass() const
1484 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001485 return holder_.GetMirrorClass(idx_);
1486 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001487 art::ObjPtr<art::mirror::Object> GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001488 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001489 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001490 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001491 art::ObjPtr<art::mirror::PointerArray> GetOldObsoleteMethods() const
Alex Light1e3926a2017-04-07 10:38:06 -07001492 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1493 return holder_.GetOldObsoleteMethods(idx_);
1494 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001495 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> GetOldDexCaches() const
Alex Light1e3926a2017-04-07 10:38:06 -07001496 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1497 return holder_.GetOldDexCaches(idx_);
1498 }
1499
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001500 art::ObjPtr<art::mirror::Class> GetNewClassObject() const
1501 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1502 return holder_.GetNewClassObject(idx_);
1503 }
1504
Alex Light986914b2019-11-19 01:12:25 +00001505 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> GetOldInstanceObjects() const
1506 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1507 return holder_.GetOldInstanceObjects(idx_);
1508 }
1509 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> GetNewInstanceObjects() const
1510 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1511 return holder_.GetNewInstanceObjects(idx_);
1512 }
Alex Light270db1c2019-12-03 12:20:01 +00001513 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> GetOldClasses() const
1514 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1515 return holder_.GetOldClasses(idx_);
1516 }
1517 art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> GetNewClasses() const
1518 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1519 return holder_.GetNewClasses(idx_);
1520 }
Alex Lightfb537082019-12-10 14:38:34 -08001521 bool IsInitialized() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1522 return holder_.IsInitialized(idx_);
1523 }
1524 bool IsActuallyStructural() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1525 return holder_.IsActuallyStructural(idx_);
1526 }
1527 bool IsInitialStructural() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
1528 return holder_.IsInitialStructural(idx_);
1529 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001530 int32_t GetIndex() const {
1531 return idx_;
1532 }
1533
1534 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1535 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1536 holder_.SetSourceClassLoader(idx_, loader);
1537 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001538 void SetJavaDexFile(art::ObjPtr<art::mirror::Object> dexfile)
1539 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001540 holder_.SetJavaDexFile(idx_, dexfile);
1541 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001542 void SetNewDexFileCookie(art::ObjPtr<art::mirror::LongArray> cookie)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001543 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1544 holder_.SetNewDexFileCookie(idx_, cookie);
1545 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001546 void SetNewDexCache(art::ObjPtr<art::mirror::DexCache> cache)
1547 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001548 holder_.SetNewDexCache(idx_, cache);
1549 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001550 void SetMirrorClass(art::ObjPtr<art::mirror::Class> klass)
1551 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001552 holder_.SetMirrorClass(idx_, klass);
1553 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001554 void SetOriginalDexFile(art::ObjPtr<art::mirror::Object> bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001555 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001556 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001557 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001558 void SetOldObsoleteMethods(art::ObjPtr<art::mirror::PointerArray> methods)
Alex Light1e3926a2017-04-07 10:38:06 -07001559 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1560 holder_.SetOldObsoleteMethods(idx_, methods);
1561 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001562 void SetOldDexCaches(art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)
Alex Light1e3926a2017-04-07 10:38:06 -07001563 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1564 holder_.SetOldDexCaches(idx_, caches);
1565 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001566 void SetNewClassObject(art::ObjPtr<art::mirror::Class> klass)
1567 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1568 holder_.SetNewClassObject(idx_, klass);
1569 }
Alex Light986914b2019-11-19 01:12:25 +00001570 void SetOldInstanceObjects(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)
1571 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1572 holder_.SetOldInstanceObjects(idx_, objs);
1573 }
1574 void SetNewInstanceObjects(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Object>> objs)
1575 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1576 holder_.SetNewInstanceObjects(idx_, objs);
1577 }
Alex Light270db1c2019-12-03 12:20:01 +00001578 void SetOldClasses(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)
1579 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1580 holder_.SetOldClasses(idx_, klasses);
1581 }
1582 void SetNewClasses(art::ObjPtr<art::mirror::ObjectArray<art::mirror::Class>> klasses)
1583 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1584 holder_.SetNewClasses(idx_, klasses);
1585 }
Alex Lightfb537082019-12-10 14:38:34 -08001586 void SetInitialized() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1587 holder_.SetInitialized(idx_);
1588 }
1589 void SetActuallyStructural() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1590 holder_.SetActuallyStructural(idx_);
1591 }
1592 void SetInitialStructural() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1593 holder_.SetInitialStructural(idx_);
1594 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001595
1596 private:
1597 int32_t idx_;
1598 RedefinitionDataHolder& holder_;
1599};
1600
1601RedefinitionDataIter RedefinitionDataHolder::begin() {
1602 return RedefinitionDataIter(0, *this);
1603}
1604
1605RedefinitionDataIter RedefinitionDataHolder::end() {
1606 return RedefinitionDataIter(Length(), *this);
1607}
1608
1609bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001610 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1611 art::StackHandleScope<2> hs(driver_->self_);
1612 std::string error;
1613 // TODO Make verification log level lower
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001614 art::verifier::FailureKind failure =
Andreas Gampea43ba3d2019-03-13 15:49:20 -07001615 art::verifier::ClassVerifier::VerifyClass(driver_->self_,
1616 dex_file_.get(),
1617 hs.NewHandle(iter.GetNewDexCache()),
1618 hs.NewHandle(GetClassLoader()),
1619 /*class_def=*/ dex_file_->GetClassDef(0),
1620 /*callbacks=*/ nullptr,
1621 /*allow_soft_failures=*/ true,
1622 /*log_level=*/
1623 art::verifier::HardFailLogMode::kLogWarning,
1624 art::Runtime::Current()->GetTargetSdkVersion(),
1625 &error);
Alex Light53330612017-10-04 15:29:53 -07001626 switch (failure) {
1627 case art::verifier::FailureKind::kNoFailure:
Alex Lightb1eebde2019-10-22 16:30:47 +00001628 // TODO It is possible that by doing redefinition previous NO_COMPILE verification failures
1629 // were fixed. It would be nice to reflect this in the new implementations.
1630 return true;
Alex Light53330612017-10-04 15:29:53 -07001631 case art::verifier::FailureKind::kSoftFailure:
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01001632 case art::verifier::FailureKind::kAccessChecksFailure:
Alex Lightb1eebde2019-10-22 16:30:47 +00001633 // Soft failures might require interpreter on some methods. It won't prevent redefinition but
1634 // it does mean we need to run the verifier again and potentially update method flags after
1635 // performing the swap.
1636 needs_reverify_ = true;
Alex Light53330612017-10-04 15:29:53 -07001637 return true;
1638 case art::verifier::FailureKind::kHardFailure: {
1639 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1640 return false;
1641 }
Alex Light8c889d22017-02-06 13:58:27 -08001642 }
Alex Light8c889d22017-02-06 13:58:27 -08001643}
1644
Alex Light1babae02017-02-01 15:35:34 -08001645// Looks through the previously allocated cookies to see if we need to update them with another new
1646// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1647// once they are all added to the classloader.
1648bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001649 art::Handle<art::mirror::ClassLoader> source_class_loader,
1650 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001651 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001652 art::StackHandleScope<2> hs(driver_->self_);
1653 art::MutableHandle<art::mirror::LongArray> old_cookie(
1654 hs.NewHandle<art::mirror::LongArray>(nullptr));
1655 bool has_older_cookie = false;
1656 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001657 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1658 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001659 // Since every instance of this classloader should have the same cookie associated with it we
1660 // can stop looking here.
1661 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001662 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001663 break;
1664 }
1665 }
1666 if (old_cookie.IsNull()) {
1667 // No older cookie. Get it directly from the dex_file_obj
1668 // We should not have seen this classloader elsewhere.
1669 CHECK(!has_older_cookie);
1670 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1671 }
1672 // Use the old cookie to generate the new one with the new DexFile* added in.
1673 art::Handle<art::mirror::LongArray>
1674 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1675 old_cookie,
1676 dex_file_.get())));
1677 // Make sure the allocation worked.
1678 if (new_cookie.IsNull()) {
1679 return false;
1680 }
1681
1682 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001683 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001684 // If there are other copies of this same classloader we need to make sure that we all have the
1685 // same cookie.
1686 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001687 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001688 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001689 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1690 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001691 }
1692 }
1693 }
1694
1695 return true;
1696}
1697
Alex Lightfb537082019-12-10 14:38:34 -08001698bool CompareClasses(art::ObjPtr<art::mirror::Class> l, art::ObjPtr<art::mirror::Class> r)
1699 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1700 auto parents = [](art::ObjPtr<art::mirror::Class> c) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1701 uint32_t res = 0;
1702 while (!c->IsObjectClass()) {
1703 res++;
1704 c = c->GetSuperClass();
1705 }
1706 return res;
1707 };
1708 return parents(l.Ptr()) < parents(r.Ptr());
1709}
1710
Alex Light986914b2019-11-19 01:12:25 +00001711bool Redefiner::ClassRedefinition::CollectAndCreateNewInstances(
1712 /*out*/ RedefinitionDataIter* cur_data) {
Alex Lightfb537082019-12-10 14:38:34 -08001713 if (!cur_data->IsInitialStructural()) {
1714 // An earlier structural redefinition already remade all the instances.
Alex Light986914b2019-11-19 01:12:25 +00001715 return true;
1716 }
Alex Lightfb537082019-12-10 14:38:34 -08001717 art::gc::Heap* heap = driver_->runtime_->GetHeap();
Alex Light986914b2019-11-19 01:12:25 +00001718 art::VariableSizedHandleScope hs(driver_->self_);
1719 art::Handle<art::mirror::Class> old_klass(hs.NewHandle(cur_data->GetMirrorClass()));
1720 std::vector<art::Handle<art::mirror::Object>> old_instances;
Alex Light986914b2019-11-19 01:12:25 +00001721 auto is_instance = [&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light270db1c2019-12-03 12:20:01 +00001722 return obj->InstanceOf(old_klass.Get());
Alex Light986914b2019-11-19 01:12:25 +00001723 };
1724 heap->VisitObjects([&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1725 if (is_instance(obj)) {
Alex Light986914b2019-11-19 01:12:25 +00001726 old_instances.push_back(hs.NewHandle(obj));
1727 }
1728 });
1729 VLOG(plugin) << "Collected " << old_instances.size() << " instances to recreate!";
Alex Light270db1c2019-12-03 12:20:01 +00001730 art::Handle<art::mirror::ObjectArray<art::mirror::Class>> old_classes_arr(
Alex Lightfb537082019-12-10 14:38:34 -08001731 hs.NewHandle(cur_data->GetOldClasses()));
Alex Light270db1c2019-12-03 12:20:01 +00001732 art::Handle<art::mirror::ObjectArray<art::mirror::Class>> new_classes_arr(
Alex Lightfb537082019-12-10 14:38:34 -08001733 hs.NewHandle(cur_data->GetNewClasses()));
Alex Light3f4041b2020-01-09 12:59:22 -08001734 DCHECK_EQ(old_classes_arr->GetLength(), new_classes_arr->GetLength());
Alex Lightbaf938f2020-01-10 10:40:46 -08001735 DCHECK_GT(old_classes_arr->GetLength(), 0);
Alex Light986914b2019-11-19 01:12:25 +00001736 art::Handle<art::mirror::Class> obj_array_class(
1737 hs.NewHandle(art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Object>>(
1738 driver_->runtime_->GetClassLinker())));
1739 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> old_instances_arr(
1740 hs.NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
1741 driver_->self_, obj_array_class.Get(), old_instances.size())));
1742 if (old_instances_arr.IsNull()) {
1743 driver_->self_->AssertPendingOOMException();
1744 driver_->self_->ClearException();
1745 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate old_instance arrays!");
1746 return false;
1747 }
1748 for (uint32_t i = 0; i < old_instances.size(); ++i) {
1749 old_instances_arr->Set(i, old_instances[i].Get());
1750 }
1751 cur_data->SetOldInstanceObjects(old_instances_arr.Get());
1752
1753 art::Handle<art::mirror::ObjectArray<art::mirror::Object>> new_instances_arr(
1754 hs.NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
1755 driver_->self_, obj_array_class.Get(), old_instances.size())));
1756 if (new_instances_arr.IsNull()) {
1757 driver_->self_->AssertPendingOOMException();
1758 driver_->self_->ClearException();
1759 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate new_instance arrays!");
1760 return false;
1761 }
Alex Light270db1c2019-12-03 12:20:01 +00001762 for (auto pair : art::ZipCount(art::IterationRange(old_instances.begin(), old_instances.end()))) {
1763 art::Handle<art::mirror::Object> hinstance(pair.first);
1764 int32_t i = pair.second;
1765 auto iterator = art::ZipLeft(old_classes_arr.Iterate<art::mirror::Class>(),
1766 new_classes_arr.Iterate<art::mirror::Class>());
Alex Lightbaf938f2020-01-10 10:40:46 -08001767 auto it = std::find_if(iterator.begin(),
1768 iterator.end(),
1769 [&](auto class_pair) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1770 return class_pair.first == hinstance->GetClass();
1771 });
1772 DCHECK(it != iterator.end()) << "Unable to find class pair for "
1773 << hinstance->GetClass()->PrettyClass() << " (instance " << i
1774 << ")";
1775 auto [_, new_type] = *it;
Alex Light2f494282020-01-07 22:53:09 +00001776 // Make sure when allocating the new instance we don't add it's finalizer since we will directly
1777 // replace the old object in the finalizer reference. If we added it here to we would call
1778 // finalize twice.
1779 // NB If a type is changed from being non-finalizable to finalizable the finalizers on any
1780 // objects created before the redefine will never be called. This is (sort of) allowable by
1781 // the spec and greatly simplifies implementation.
1782 // TODO Make it so we will always call all finalizers, even if the object when it was created
1783 // wasn't finalizable. To do this we need to be careful of handling failure correctly and making
1784 // sure that objects aren't finalized multiple times and that instances of failed redefinitions
1785 // aren't finalized.
1786 art::ObjPtr<art::mirror::Object> new_instance(
1787 new_type->Alloc</*kIsInstrumented=*/true,
1788 art::mirror::Class::AddFinalizer::kNoAddFinalizer,
1789 /*kCheckAddFinalizer=*/false>(
1790 driver_->self_, driver_->runtime_->GetHeap()->GetCurrentAllocator()));
Alex Light986914b2019-11-19 01:12:25 +00001791 if (new_instance.IsNull()) {
1792 driver_->self_->AssertPendingOOMException();
1793 driver_->self_->ClearException();
1794 std::string msg(
1795 StringPrintf("Could not allocate instance %d of %zu", i, old_instances.size()));
1796 RecordFailure(ERR(OUT_OF_MEMORY), msg);
1797 return false;
1798 }
1799 new_instances_arr->Set(i, new_instance);
1800 }
1801 cur_data->SetNewInstanceObjects(new_instances_arr.Get());
1802 return true;
1803}
1804
Alex Lightfb537082019-12-10 14:38:34 -08001805bool Redefiner::ClassRedefinition::FinishRemainingCommonAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001806 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001807 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lightfb537082019-12-10 14:38:34 -08001808 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001809 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001810 // This shouldn't allocate
1811 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001812 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1813 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001814 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001815 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1816 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001817 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001818 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001819 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1820 return false;
1821 }
Alex Light1babae02017-02-01 15:35:34 -08001822 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001823 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001824 driver_->self_->AssertPendingOOMException();
1825 driver_->self_->ClearException();
1826 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1827 return false;
1828 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001829 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001830 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1831 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001832 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001833 driver_->self_->ClearException();
1834 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1835 return false;
1836 }
1837
1838 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001839 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1840 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001841 driver_->self_->AssertPendingOOMException();
1842 driver_->self_->ClearException();
1843 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1844 return false;
1845 }
Alex Lightfb537082019-12-10 14:38:34 -08001846 return true;
1847}
1848
1849bool Redefiner::ClassRedefinition::FinishNewClassAllocations(RedefinitionDataHolder &holder,
1850 RedefinitionDataIter *cur_data) {
1851 if (cur_data->IsInitialized() || !cur_data->IsActuallyStructural()) {
1852 cur_data->SetInitialized();
1853 return true;
1854 }
1855
1856 art::VariableSizedHandleScope hs(driver_->self_);
1857 // If we weren't the lowest structural redef the superclass would have already initialized us.
1858 CHECK(IsStructuralRedefinition());
1859 CHECK(cur_data->IsInitialStructural()) << "Should have already been initialized by supertype";
1860 auto setup_single_redefinition =
1861 [this](RedefinitionDataIter* data, art::Handle<art::mirror::Class> super_class)
1862 REQUIRES_SHARED(art::Locks::mutator_lock_) -> art::ObjPtr<art::mirror::Class> {
1863 art::StackHandleScope<3> chs(driver_->self_);
1864 art::Handle<art::mirror::Class> nc(
1865 chs.NewHandle(AllocateNewClassObject(chs.NewHandle(data->GetMirrorClass()),
1866 super_class,
1867 chs.NewHandle(data->GetNewDexCache()),
1868 /*dex_class_def_index*/ 0)));
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001869 if (nc.IsNull()) {
Alex Lightfb537082019-12-10 14:38:34 -08001870 return nullptr;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001871 }
1872
Alex Lightfb537082019-12-10 14:38:34 -08001873 data->SetNewClassObject(nc.Get());
Alex Light24627892019-11-06 10:28:21 -08001874 // We really want to be able to resolve to the new class-object using this dex-cache for
1875 // verification work. Since we haven't put it in the class-table yet we wll just manually add it
1876 // to the dex-cache.
1877 // TODO: We should maybe do this in a better spot.
Alex Lightfb537082019-12-10 14:38:34 -08001878 data->GetNewDexCache()->SetResolvedType(nc->GetDexTypeIndex(), nc.Get());
1879 data->SetInitialized();
1880 return nc.Get();
1881 };
1882
1883 std::vector<art::Handle<art::mirror::Class>> old_types;
1884 {
1885 art::gc::Heap* heap = driver_->runtime_->GetHeap();
1886 art::Handle<art::mirror::Class>
1887 old_klass(hs.NewHandle(cur_data->GetMirrorClass()));
1888 if (setup_single_redefinition(cur_data, hs.NewHandle(old_klass->GetSuperClass())).IsNull()) {
1889 return false;
1890 }
1891 auto is_subtype = [&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1892 // We've already waited for class defines to be finished and paused them. All classes should be
1893 // either resolved or error. We don't need to do anything with error classes, since they cannot
1894 // be accessed in any observable way.
1895 return obj->IsClass() && obj->AsClass()->IsResolved() &&
1896 old_klass->IsAssignableFrom(obj->AsClass());
1897 };
1898 heap->VisitObjects([&](art::mirror::Object* obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1899 if (is_subtype(obj)) {
1900 old_types.push_back(hs.NewHandle(obj->AsClass()));
1901 }
1902 });
Alex Lightbaf938f2020-01-10 10:40:46 -08001903 DCHECK_GT(old_types.size(), 0u) << "Expected to find at least old_klass!";
Alex Lightfb537082019-12-10 14:38:34 -08001904 VLOG(plugin) << "Found " << old_types.size() << " types that are/are subtypes of "
1905 << old_klass->PrettyClass();
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001906 }
Alex Lightfb537082019-12-10 14:38:34 -08001907
1908 art::Handle<art::mirror::Class> cls_array_class(
1909 hs.NewHandle(art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Class>>(
1910 driver_->runtime_->GetClassLinker())));
1911 art::Handle<art::mirror::ObjectArray<art::mirror::Class>> old_classes_arr(
1912 hs.NewHandle(art::mirror::ObjectArray<art::mirror::Class>::Alloc(
1913 driver_->self_, cls_array_class.Get(), old_types.size())));
1914 if (old_classes_arr.IsNull()) {
1915 driver_->self_->AssertPendingOOMException();
1916 driver_->self_->ClearException();
1917 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate old_classes arrays!");
1918 return false;
1919 }
1920 // Sort the old_types topologically.
1921 {
1922 art::ScopedAssertNoThreadSuspension sants("Sort classes");
1923 // Sort them by the distance to the base-class. This ensures that any class occurs before any of
1924 // its subtypes.
1925 std::sort(old_types.begin(),
1926 old_types.end(),
1927 [](auto& l, auto& r) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1928 return CompareClasses(l.Get(), r.Get());
1929 });
1930 }
1931 for (uint32_t i = 0; i < old_types.size(); ++i) {
Alex Lightbaf938f2020-01-10 10:40:46 -08001932 DCHECK(!old_types[i].IsNull()) << i;
Alex Lightfb537082019-12-10 14:38:34 -08001933 old_classes_arr->Set(i, old_types[i].Get());
1934 }
1935 cur_data->SetOldClasses(old_classes_arr.Get());
Alex Lightbaf938f2020-01-10 10:40:46 -08001936 DCHECK_GT(old_classes_arr->GetLength(), 0);
Alex Lightfb537082019-12-10 14:38:34 -08001937
1938 art::Handle<art::mirror::ObjectArray<art::mirror::Class>> new_classes_arr(
1939 hs.NewHandle(art::mirror::ObjectArray<art::mirror::Class>::Alloc(
1940 driver_->self_, cls_array_class.Get(), old_types.size())));
1941 if (new_classes_arr.IsNull()) {
1942 driver_->self_->AssertPendingOOMException();
1943 driver_->self_->ClearException();
1944 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate new_classes arrays!");
1945 return false;
1946 }
1947
1948 art::MutableHandle<art::mirror::DexCache> dch(hs.NewHandle<art::mirror::DexCache>(nullptr));
1949 art::MutableHandle<art::mirror::Class> superclass(hs.NewHandle<art::mirror::Class>(nullptr));
1950 for (size_t i = 0; i < old_types.size(); i++) {
1951 art::Handle<art::mirror::Class>& old_type = old_types[i];
1952 if (old_type.Get() == cur_data->GetMirrorClass()) {
1953 CHECK_EQ(i, 0u) << "original class not at index 0. Bad sort!";
1954 new_classes_arr->Set(i, cur_data->GetNewClassObject());
1955 continue;
1956 } else {
1957 auto old_super = std::find_if(old_types.begin(),
1958 old_types.begin() + i,
1959 [&](art::Handle<art::mirror::Class>& v)
1960 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1961 return v.Get() == old_type->GetSuperClass();
1962 });
1963 // Only the GetMirrorClass should not be in this list.
1964 CHECK(old_super != old_types.begin() + i)
1965 << "from first " << i << " could not find super of " << old_type->PrettyClass()
1966 << " expected to find " << old_type->GetSuperClass()->PrettyClass();
1967 superclass.Assign(new_classes_arr->Get(std::distance(old_types.begin(), old_super)));
1968 auto new_redef = std::find_if(
1969 *cur_data + 1, holder.end(), [&](auto it) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1970 return it.GetMirrorClass() == old_type.Get();
1971 });
1972 art::ObjPtr<art::mirror::Class> new_type;
1973 if (new_redef == holder.end()) {
1974 // We aren't also redefining this subclass. Just allocate a new class and continue.
1975 dch.Assign(old_type->GetDexCache());
1976 new_type =
1977 AllocateNewClassObject(old_type, superclass, dch, old_type->GetDexClassDefIndex());
1978 } else {
1979 // This subclass is also being redefined. We need to use its new dex-file to load the new
1980 // class.
1981 CHECK(new_redef.IsActuallyStructural());
1982 CHECK(!new_redef.IsInitialStructural());
1983 new_type = setup_single_redefinition(&new_redef, superclass);
1984 }
1985 if (new_type == nullptr) {
1986 VLOG(plugin) << "Failed to load new version of class " << old_type->PrettyClass()
1987 << " for structural redefinition!";
1988 return false;
1989 }
1990 new_classes_arr->Set(i, new_type);
1991 }
1992 }
1993 cur_data->SetNewClasses(new_classes_arr.Get());
Alex Lighta7e38d82017-01-19 14:57:28 -08001994 return true;
1995}
1996
Alex Light270db1c2019-12-03 12:20:01 +00001997uint32_t Redefiner::ClassRedefinition::GetNewClassSize(art::ClassAccessor& accessor) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00001998 uint32_t num_8bit_static_fields = 0;
1999 uint32_t num_16bit_static_fields = 0;
2000 uint32_t num_32bit_static_fields = 0;
2001 uint32_t num_64bit_static_fields = 0;
2002 uint32_t num_ref_static_fields = 0;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002003 for (const art::ClassAccessor::Field& f : accessor.GetStaticFields()) {
Alex Light270db1c2019-12-03 12:20:01 +00002004 std::string_view desc(accessor.GetDexFile().GetFieldTypeDescriptor(
2005 accessor.GetDexFile().GetFieldId(f.GetIndex())));
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002006 if (desc[0] == 'L' || desc[0] == '[') {
2007 num_ref_static_fields++;
2008 } else if (desc == "Z" || desc == "B") {
2009 num_8bit_static_fields++;
2010 } else if (desc == "C" || desc == "S") {
2011 num_16bit_static_fields++;
2012 } else if (desc == "I" || desc == "F") {
2013 num_32bit_static_fields++;
2014 } else if (desc == "J" || desc == "D") {
2015 num_64bit_static_fields++;
2016 } else {
2017 LOG(FATAL) << "Unknown type descriptor! " << desc;
2018 }
2019 }
2020
Alex Light270db1c2019-12-03 12:20:01 +00002021 return art::mirror::Class::ComputeClassSize(/*has_embedded_vtable=*/ false,
2022 /*num_vtable_entries=*/ 0,
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002023 num_8bit_static_fields,
2024 num_16bit_static_fields,
2025 num_32bit_static_fields,
2026 num_64bit_static_fields,
2027 num_ref_static_fields,
2028 art::kRuntimePointerSize);
2029}
2030
2031art::ObjPtr<art::mirror::Class>
2032Redefiner::ClassRedefinition::AllocateNewClassObject(art::Handle<art::mirror::DexCache> cache) {
Alex Light270db1c2019-12-03 12:20:01 +00002033 art::StackHandleScope<2> hs(driver_->self_);
2034 art::Handle<art::mirror::Class> old_class(hs.NewHandle(GetMirrorClass()));
2035 art::Handle<art::mirror::Class> super_class(hs.NewHandle(old_class->GetSuperClass()));
2036 return AllocateNewClassObject(old_class, super_class, cache, /*dex_class_def_index*/0);
2037}
2038
2039art::ObjPtr<art::mirror::Class> Redefiner::ClassRedefinition::AllocateNewClassObject(
2040 art::Handle<art::mirror::Class> old_class,
2041 art::Handle<art::mirror::Class> super_class,
2042 art::Handle<art::mirror::DexCache> cache,
2043 uint16_t dex_class_def_index) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002044 // This is a stripped down DefineClass. We don't want to use DefineClass directly because it needs
2045 // to perform a lot of extra steps to tell the ClassTable and the jit and everything about a new
2046 // class. For now we will need to rely on our tests catching any issues caused by changes in how
2047 // class_linker sets up classes.
2048 // TODO Unify/move this into ClassLinker maybe.
Alex Light270db1c2019-12-03 12:20:01 +00002049 art::StackHandleScope<3> hs(driver_->self_);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002050 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Light270db1c2019-12-03 12:20:01 +00002051 const art::DexFile* dex_file = cache->GetDexFile();
2052 art::ClassAccessor accessor(*dex_file, dex_class_def_index);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002053 art::Handle<art::mirror::Class> new_class(hs.NewHandle(linker->AllocClass(
Alex Light270db1c2019-12-03 12:20:01 +00002054 driver_->self_, GetNewClassSize(accessor))));
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002055 if (new_class.IsNull()) {
2056 driver_->self_->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00002057 RecordFailure(
2058 ERR(OUT_OF_MEMORY),
2059 "Unable to allocate class object for redefinition of " + old_class->PrettyClass());
2060 driver_->self_->ClearException();
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002061 return nullptr;
2062 }
2063 new_class->SetDexCache(cache.Get());
Alex Light270db1c2019-12-03 12:20:01 +00002064 linker->SetupClass(*dex_file,
2065 dex_file->GetClassDef(dex_class_def_index),
2066 new_class,
2067 old_class->GetClassLoader());
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002068
2069 // Make sure we are ready for linking. The lock isn't really needed since this isn't visible to
2070 // other threads but the linker expects it.
2071 art::ObjectLock<art::mirror::Class> lock(driver_->self_, new_class);
2072 new_class->SetClinitThreadId(driver_->self_->GetTid());
2073 // Make sure we have a valid empty iftable even if there are errors.
2074 new_class->SetIfTable(art::GetClassRoot<art::mirror::Object>(linker)->GetIfTable());
Alex Light270db1c2019-12-03 12:20:01 +00002075 linker->LoadClass(
2076 driver_->self_, *dex_file, dex_file->GetClassDef(dex_class_def_index), new_class);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002077 // NB. We know the interfaces and supers didn't change! :)
2078 art::MutableHandle<art::mirror::Class> linked_class(hs.NewHandle<art::mirror::Class>(nullptr));
2079 art::Handle<art::mirror::ObjectArray<art::mirror::Class>> proxy_ifaces(
2080 hs.NewHandle<art::mirror::ObjectArray<art::mirror::Class>>(nullptr));
2081 // No changing hierarchy so everything is loaded.
Alex Light270db1c2019-12-03 12:20:01 +00002082 new_class->SetSuperClass(super_class.Get());
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002083 art::mirror::Class::SetStatus(new_class, art::ClassStatus::kLoaded, nullptr);
2084 if (!linker->LinkClass(driver_->self_, nullptr, new_class, proxy_ifaces, &linked_class)) {
Alex Light270db1c2019-12-03 12:20:01 +00002085 std::ostringstream oss;
2086 oss << "failed to link class due to "
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002087 << (driver_->self_->IsExceptionPending() ? driver_->self_->GetException()->Dump()
2088 : " unknown");
Alex Light270db1c2019-12-03 12:20:01 +00002089 RecordFailure(ERR(INTERNAL), oss.str());
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002090 driver_->self_->ClearException();
2091 return nullptr;
2092 }
Alex Light270db1c2019-12-03 12:20:01 +00002093 // Everything is already resolved.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002094 art::ObjectLock<art::mirror::Class> objlock(driver_->self_, linked_class);
Alex Lightfb119572019-09-18 15:04:53 -07002095 // Mark the class as initialized.
Alex Light270db1c2019-12-03 12:20:01 +00002096 CHECK(old_class->IsResolved())
2097 << "Attempting to redefine an unresolved class " << old_class->PrettyClass()
Alex Lightfb119572019-09-18 15:04:53 -07002098 << " status=" << old_class->GetStatus();
Alex Light270db1c2019-12-03 12:20:01 +00002099 CHECK(linked_class->IsResolved());
2100 if (old_class->WasVerificationAttempted()) {
2101 // Match verification-attempted flag
2102 linked_class->SetVerificationAttempted();
2103 }
2104 if (old_class->ShouldSkipHiddenApiChecks()) {
2105 // Match skip hiddenapi flag
2106 linked_class->SetSkipHiddenApiChecks();
2107 }
2108 if (old_class->IsInitialized()) {
2109 // We already verified the class earlier. No need to do it again.
2110 linker->ForceClassInitialized(driver_->self_, linked_class);
2111 } else if (old_class->GetStatus() > linked_class->GetStatus()) {
2112 // We want to match the old status.
2113 art::mirror::Class::SetStatus(linked_class, old_class->GetStatus(), driver_->self_);
2114 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002115 // Make sure we have ext-data space for method & field ids. We won't know if we need them until
2116 // it's too late to create them.
2117 // TODO We might want to remove these arrays if they're not needed.
Alex Lightbc19b752019-12-02 18:54:13 +00002118 if (!art::mirror::Class::EnsureInstanceFieldIds(linked_class) ||
2119 !art::mirror::Class::EnsureStaticFieldIds(linked_class) ||
2120 !art::mirror::Class::EnsureMethodIds(linked_class)) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002121 driver_->self_->AssertPendingOOMException();
2122 driver_->self_->ClearException();
Alex Light270db1c2019-12-03 12:20:01 +00002123 RecordFailure(
2124 ERR(OUT_OF_MEMORY),
2125 "Unable to allocate jni-id arrays for redefinition of " + old_class->PrettyClass());
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002126 return nullptr;
2127 }
2128 // Finish setting up methods.
2129 linked_class->VisitMethods([&](art::ArtMethod* m) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2130 linker->SetEntryPointsToInterpreter(m);
2131 m->SetNotIntrinsic();
2132 DCHECK(m->IsCopied() || m->GetDeclaringClass() == linked_class.Get())
2133 << m->PrettyMethod()
2134 << " m->GetDeclaringClass(): " << m->GetDeclaringClass()->PrettyClass()
2135 << " != linked_class.Get(): " << linked_class->PrettyClass();
2136 }, art::kRuntimePointerSize);
2137 if (art::kIsDebugBuild) {
2138 linked_class->VisitFields([&](art::ArtField* f) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2139 DCHECK_EQ(f->GetDeclaringClass(), linked_class.Get());
2140 });
2141 }
Alex Light270db1c2019-12-03 12:20:01 +00002142 // Reset ClinitThreadId back to the thread that loaded the old class. This is needed if we are in
2143 // the middle of initializing a class.
2144 linked_class->SetClinitThreadId(old_class->GetClinitThreadId());
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002145 return linked_class.Get();
2146}
2147
Alex Lighta26e3492017-06-27 17:55:37 -07002148void Redefiner::ClassRedefinition::UnregisterJvmtiBreakpoints() {
Vladimir Marko4617d582019-03-28 13:48:31 +00002149 BreakpointUtil::RemoveBreakpointsInClass(driver_->env_, GetMirrorClass().Ptr());
Alex Lighta26e3492017-06-27 17:55:37 -07002150}
2151
Alex Light5643caf2017-02-08 11:39:07 -08002152void Redefiner::UnregisterAllBreakpoints() {
Alex Light5643caf2017-02-08 11:39:07 -08002153 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
Alex Lighte34fe442018-02-21 17:35:55 -08002154 redef.UnregisterJvmtiBreakpoints();
Alex Light5643caf2017-02-08 11:39:07 -08002155 }
2156}
2157
Alex Light0e692732017-01-10 15:00:05 -08002158bool Redefiner::CheckAllRedefinitionAreValid() {
2159 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
2160 if (!redef.CheckRedefinitionIsValid()) {
2161 return false;
2162 }
2163 }
2164 return true;
2165}
2166
Alex Light1e3926a2017-04-07 10:38:06 -07002167void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
2168 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2169 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
2170 }
2171}
2172
Alex Lightfb537082019-12-10 14:38:34 -08002173void Redefiner::MarkStructuralChanges(RedefinitionDataHolder& holder) {
2174 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2175 if (data.IsActuallyStructural()) {
2176 // A superclass was structural and it marked all subclasses already. No need to do anything.
2177 CHECK(!data.IsInitialStructural());
2178 } else if (data.GetRedefinition().IsStructuralRedefinition()) {
2179 data.SetActuallyStructural();
2180 data.SetInitialStructural();
2181 // Go over all potential subtypes and mark any that are actually subclasses as structural.
2182 for (RedefinitionDataIter sub_data = data + 1; sub_data != holder.end(); ++sub_data) {
2183 if (sub_data.GetRedefinition().GetMirrorClass()->IsSubClass(
2184 data.GetRedefinition().GetMirrorClass())) {
2185 sub_data.SetActuallyStructural();
2186 }
2187 }
2188 }
2189 }
2190}
2191
Alex Light1e3926a2017-04-07 10:38:06 -07002192bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
2193 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2194 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08002195 return false;
2196 }
2197 }
2198 return true;
2199}
2200
Alex Light986914b2019-11-19 01:12:25 +00002201bool Redefiner::CollectAndCreateNewInstances(RedefinitionDataHolder& holder) {
2202 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2203 // Allocate the data this redefinition requires.
2204 if (!data.GetRedefinition().CollectAndCreateNewInstances(&data)) {
2205 return false;
2206 }
2207 }
2208 return true;
2209}
2210
Alex Lightfb537082019-12-10 14:38:34 -08002211bool Redefiner::FinishAllNewClassAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08002212 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08002213 // Allocate the data this redefinition requires.
Alex Lightfb537082019-12-10 14:38:34 -08002214 if (!data.GetRedefinition().FinishNewClassAllocations(holder, &data)) {
2215 return false;
2216 }
2217 }
2218 return true;
2219}
2220
2221bool Redefiner::FinishAllRemainingCommonAllocations(RedefinitionDataHolder& holder) {
2222 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2223 // Allocate the data this redefinition requires.
2224 if (!data.GetRedefinition().FinishRemainingCommonAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08002225 return false;
2226 }
Alex Light0e692732017-01-10 15:00:05 -08002227 }
2228 return true;
2229}
2230
2231void Redefiner::ClassRedefinition::ReleaseDexFile() {
Andreas Gampeafaf7f82018-10-16 11:32:38 -07002232 dex_file_.release(); // NOLINT b/117926937
Alex Light0e692732017-01-10 15:00:05 -08002233}
2234
2235void Redefiner::ReleaseAllDexFiles() {
2236 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
2237 redef.ReleaseDexFile();
2238 }
2239}
2240
Alex Lightc5f5a6e2017-03-01 16:57:08 -08002241bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
2242 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2243 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08002244 return false;
2245 }
Alex Light8c889d22017-02-06 13:58:27 -08002246 }
2247 return true;
2248}
2249
Alex Lightc5f5a6e2017-03-01 16:57:08 -08002250class ScopedDisableConcurrentAndMovingGc {
2251 public:
2252 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
2253 : heap_(heap), self_(self) {
2254 if (heap_->IsGcConcurrentAndMoving()) {
2255 heap_->IncrementDisableMovingGC(self_);
2256 }
2257 }
2258
2259 ~ScopedDisableConcurrentAndMovingGc() {
2260 if (heap_->IsGcConcurrentAndMoving()) {
2261 heap_->DecrementDisableMovingGC(self_);
2262 }
2263 }
2264 private:
2265 art::gc::Heap* heap_;
2266 art::Thread* self_;
2267};
2268
Alex Light270db1c2019-12-03 12:20:01 +00002269class ClassDefinitionPauser : public art::ClassLoadCallback {
2270 public:
2271 explicit ClassDefinitionPauser(art::Thread* self) REQUIRES_SHARED(art::Locks::mutator_lock_)
2272 : self_(self),
2273 is_running_(false),
2274 barrier_(0),
2275 release_mu_("SuspendClassDefinition lock", art::kGenericBottomLock),
2276 release_barrier_(0),
2277 release_cond_("SuspendClassDefinition condvar", release_mu_),
2278 count_(0),
2279 release_(false) {
2280 art::Locks::mutator_lock_->AssertSharedHeld(self_);
2281 }
2282 ~ClassDefinitionPauser() REQUIRES_SHARED(art::Locks::mutator_lock_) {
2283 art::Locks::mutator_lock_->AssertSharedHeld(self_);
Alex Lightf6c69e52020-01-17 15:30:40 -08002284 CHECK(release_) << "Must call Release()";
2285 }
2286 void Release() REQUIRES(art::Locks::mutator_lock_) {
Alex Light270db1c2019-12-03 12:20:01 +00002287 if (is_running_) {
Alex Lightf6c69e52020-01-17 15:30:40 -08002288 art::Locks::mutator_lock_->AssertExclusiveHeld(self_);
Alex Light270db1c2019-12-03 12:20:01 +00002289 uint32_t count;
2290 // Wake up everything.
2291 {
2292 art::MutexLock mu(self_, release_mu_);
2293 release_ = true;
Alex Lightf6c69e52020-01-17 15:30:40 -08002294 // We have an exclusive mutator so all threads must be suspended and therefore they've
2295 // either already incremented this count_ or they are stuck somewhere before it.
Alex Light270db1c2019-12-03 12:20:01 +00002296 count = count_;
2297 release_cond_.Broadcast(self_);
2298 }
2299 // Wait for all threads to leave this structs code.
Alex Light270db1c2019-12-03 12:20:01 +00002300 VLOG(plugin) << "Resuming " << count << " threads paused before class-allocation!";
Alex Lightf6c69e52020-01-17 15:30:40 -08002301 release_barrier_.Increment</*locks=*/art::Barrier::kAllowHoldingLocks>(self_, count);
2302 } else {
2303 release_ = true;
Alex Light270db1c2019-12-03 12:20:01 +00002304 }
2305 }
2306 void BeginDefineClass() override REQUIRES_SHARED(art::Locks::mutator_lock_) {
2307 art::Thread* this_thread = art::Thread::Current();
2308 if (this_thread == self_) {
2309 // Allow the redefining thread to do whatever.
2310 return;
2311 }
2312 if (this_thread->GetDefineClassCount() != 0) {
2313 // We are in the middle of a recursive define-class. Don't suspend now allow it to finish.
2314 VLOG(plugin) << "Recursive DefineClass in " << *this_thread
2315 << " allowed to proceed despite class-def pause initiated by " << *self_;
2316 return;
2317 }
Alex Lightf6c69e52020-01-17 15:30:40 -08002318 // If we are suspended (no mutator-lock) then the pausing thread could do everything before the
2319 // count_++ including destroying this object, causing UAF/deadlock.
2320 art::Locks::mutator_lock_->AssertSharedHeld(this_thread);
2321 ++count_;
Alex Light270db1c2019-12-03 12:20:01 +00002322 art::ScopedThreadSuspension sts(this_thread, art::ThreadState::kSuspended);
2323 {
2324 art::MutexLock mu(this_thread, release_mu_);
Alex Light270db1c2019-12-03 12:20:01 +00002325 VLOG(plugin) << "Suspending " << *this_thread << " due to class definition. class-def pause "
2326 << "initiated by " << *self_;
Alex Light270db1c2019-12-03 12:20:01 +00002327 while (!release_) {
2328 release_cond_.Wait(this_thread);
2329 }
2330 }
2331 release_barrier_.Pass(this_thread);
2332 }
Alex Lightf6c69e52020-01-17 15:30:40 -08002333
Alex Light270db1c2019-12-03 12:20:01 +00002334 void EndDefineClass() override REQUIRES_SHARED(art::Locks::mutator_lock_) {
2335 art::Thread* this_thread = art::Thread::Current();
2336 if (this_thread == self_) {
2337 // Allow the redefining thread to do whatever.
2338 return;
2339 }
2340 if (this_thread->GetDefineClassCount() == 0) {
2341 // We are done with defining classes.
2342 barrier_.Pass(this_thread);
2343 }
2344 }
2345
2346 void ClassLoad(art::Handle<art::mirror::Class> klass ATTRIBUTE_UNUSED) override {}
2347 void ClassPrepare(art::Handle<art::mirror::Class> klass1 ATTRIBUTE_UNUSED,
2348 art::Handle<art::mirror::Class> klass2 ATTRIBUTE_UNUSED) override {}
2349
2350 void SetRunning() {
2351 is_running_ = true;
2352 }
2353 void WaitFor(uint32_t t) REQUIRES(!art::Locks::mutator_lock_) {
2354 barrier_.Increment(self_, t);
2355 }
2356
2357 private:
2358 art::Thread* self_;
2359 bool is_running_;
2360 art::Barrier barrier_;
2361 art::Mutex release_mu_;
2362 art::Barrier release_barrier_;
2363 art::ConditionVariable release_cond_;
Alex Lightf6c69e52020-01-17 15:30:40 -08002364 std::atomic<uint32_t> count_;
Alex Light270db1c2019-12-03 12:20:01 +00002365 bool release_;
2366};
2367
2368class ScopedSuspendClassLoading {
2369 public:
2370 ScopedSuspendClassLoading(art::Thread* self, art::Runtime* runtime, RedefinitionDataHolder& h)
2371 REQUIRES_SHARED(art::Locks::mutator_lock_)
Alex Lightf6c69e52020-01-17 15:30:40 -08002372 : self_(self), runtime_(runtime), pauser_() {
Alex Light270db1c2019-12-03 12:20:01 +00002373 if (std::any_of(h.begin(), h.end(), [](auto r) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2374 return r.GetRedefinition().IsStructuralRedefinition();
2375 })) {
2376 VLOG(plugin) << "Pausing Class loading for structural redefinition.";
Alex Lightf6c69e52020-01-17 15:30:40 -08002377 pauser_.emplace(self);
Alex Light270db1c2019-12-03 12:20:01 +00002378 {
2379 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
2380 uint32_t in_progress_defines = 0;
2381 {
2382 art::ScopedSuspendAll ssa(__FUNCTION__);
Alex Lightf6c69e52020-01-17 15:30:40 -08002383 pauser_->SetRunning();
2384 runtime_->GetRuntimeCallbacks()->AddClassLoadCallback(&pauser_.value());
Alex Light270db1c2019-12-03 12:20:01 +00002385 art::MutexLock mu(self_, *art::Locks::thread_list_lock_);
2386 runtime_->GetThreadList()->ForEach([&](art::Thread* t) {
2387 if (t != self_ && t->GetDefineClassCount() != 0) {
2388 in_progress_defines++;
2389 }
2390 });
Alex Lightf6c69e52020-01-17 15:30:40 -08002391 VLOG(plugin) << "Waiting for " << in_progress_defines
2392 << " in progress class-loads to finish";
Alex Light270db1c2019-12-03 12:20:01 +00002393 }
Alex Lightf6c69e52020-01-17 15:30:40 -08002394 pauser_->WaitFor(in_progress_defines);
Alex Light270db1c2019-12-03 12:20:01 +00002395 }
2396 }
2397 }
2398 ~ScopedSuspendClassLoading() {
Alex Lightf6c69e52020-01-17 15:30:40 -08002399 if (pauser_.has_value()) {
Alex Light270db1c2019-12-03 12:20:01 +00002400 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
2401 art::ScopedSuspendAll ssa(__FUNCTION__);
Alex Lightf6c69e52020-01-17 15:30:40 -08002402 pauser_->Release();
2403 runtime_->GetRuntimeCallbacks()->RemoveClassLoadCallback(&pauser_.value());
Alex Light270db1c2019-12-03 12:20:01 +00002404 }
2405 }
2406
2407 private:
2408 art::Thread* self_;
2409 art::Runtime* runtime_;
Alex Lightf6c69e52020-01-17 15:30:40 -08002410 std::optional<ClassDefinitionPauser> pauser_;
Alex Light270db1c2019-12-03 12:20:01 +00002411};
2412
Alex Light986914b2019-11-19 01:12:25 +00002413class ScopedSuspendAllocations {
2414 public:
2415 ScopedSuspendAllocations(art::Runtime* runtime, RedefinitionDataHolder& h)
2416 REQUIRES_SHARED(art::Locks::mutator_lock_)
2417 : paused_(false) {
2418 if (std::any_of(h.begin(),
2419 h.end(),
2420 [](auto r) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2421 return r.GetRedefinition().IsStructuralRedefinition();
2422 })) {
2423 VLOG(plugin) << "Pausing allocations for structural redefinition.";
2424 paused_ = true;
2425 AllocationManager::Get()->PauseAllocations(art::Thread::Current());
2426 // Collect garbage so we don't need to recreate as much.
2427 runtime->GetHeap()->CollectGarbage(/*clear_soft_references=*/false);
2428 }
2429 }
2430
2431 ~ScopedSuspendAllocations() REQUIRES_SHARED(art::Locks::mutator_lock_) {
2432 if (paused_) {
2433 AllocationManager::Get()->ResumeAllocations(art::Thread::Current());
2434 }
2435 }
2436
2437 private:
2438 bool paused_;
2439
2440 DISALLOW_COPY_AND_ASSIGN(ScopedSuspendAllocations);
2441};
2442
Alex Lighta01de592016-11-15 10:43:06 -08002443jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08002444 art::StackHandleScope<1> hs(self_);
Alex Lightfb537082019-12-10 14:38:34 -08002445 // Sort the redefinitions_ array topologically by class. This makes later steps easier since we
2446 // know that every class precedes all of its supertypes.
2447 std::sort(redefinitions_.begin(),
2448 redefinitions_.end(),
2449 [&](auto& l, auto& r) REQUIRES_SHARED(art::Locks::mutator_lock_) {
2450 return CompareClasses(l.GetMirrorClass(), r.GetMirrorClass());
2451 });
2452 // Allocate an array to hold onto all java temporary objects associated with this
2453 // redefinition. We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08002454 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08002455 if (holder.IsNull()) {
2456 self_->AssertPendingOOMException();
2457 self_->ClearException();
2458 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
2459 return result_;
2460 }
2461
Alex Lighta01de592016-11-15 10:43:06 -08002462 // First we just allocate the ClassExt and its fields that we need. These can be updated
Alex Lightfb537082019-12-10 14:38:34 -08002463 // atomically without any issues (since we allocate the map arrays as empty).
2464 if (!CheckAllRedefinitionAreValid()) {
2465 return result_;
2466 }
2467 // Mark structural changes.
2468 MarkStructuralChanges(holder);
2469 // Now we pause class loading. If we are doing a structural redefinition we will need to get an
2470 // accurate picture of the classes loaded and having loads in the middle would make that
2471 // impossible. This only pauses class-loading if we actually have at least one structural
2472 // redefinition.
2473 ScopedSuspendClassLoading suspend_class_load(self_, runtime_, holder);
2474 if (!EnsureAllClassAllocationsFinished(holder) ||
2475 !FinishAllRemainingCommonAllocations(holder) ||
2476 !FinishAllNewClassAllocations(holder) ||
Alex Light8c889d22017-02-06 13:58:27 -08002477 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08002478 return result_;
2479 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08002480
Alex Light986914b2019-11-19 01:12:25 +00002481 ScopedSuspendAllocations suspend_alloc(runtime_, holder);
2482 if (!CollectAndCreateNewInstances(holder)) {
2483 return result_;
2484 }
2485
Alex Light5643caf2017-02-08 11:39:07 -08002486 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08002487 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light07f06212017-06-01 14:01:43 -07002488 art::ClassLinker* cl = runtime_->GetClassLinker();
2489 cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
Alex Lightc5f5a6e2017-03-01 16:57:08 -08002490 if (data.GetSourceClassLoader() == nullptr) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002491 cl->AppendToBootClassPath(self_, &data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08002492 }
Alex Light7916f202017-01-27 09:00:15 -08002493 }
Alex Light5643caf2017-02-08 11:39:07 -08002494 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08002495
Alex Lightc2d0c962019-10-23 14:14:25 -07002496 {
2497 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
2498 // allocating so no deadlocks.
2499 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08002500
Alex Lightc2d0c962019-10-23 14:14:25 -07002501 // Do transition to final suspension
2502 // TODO We might want to give this its own suspended state!
2503 // TODO This isn't right. We need to change state without any chance of suspend ideally!
2504 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
2505 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend=*/true);
2506 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2507 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
2508 ClassRedefinition& redef = data.GetRedefinition();
2509 if (data.GetSourceClassLoader() != nullptr) {
2510 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
2511 }
2512 redef.UpdateClass(data);
Alex Light7916f202017-01-27 09:00:15 -08002513 }
Alex Lightc2d0c962019-10-23 14:14:25 -07002514 RestoreObsoleteMethodMapsIfUnneeded(holder);
2515 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if
2516 // any are, force a full-world deoptimization before finishing redefinition. If we don't do this
2517 // then methods that have been jitted prior to the current redefinition being applied might
2518 // continue to use the old versions of the intrinsics!
2519 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
2520 // owns the DexFile and when ownership is transferred.
2521 ReleaseAllDexFiles();
Alex Light0e692732017-01-10 15:00:05 -08002522 }
Alex Lightb1eebde2019-10-22 16:30:47 +00002523 // By now the class-linker knows about all the classes so we can safetly retry verification and
2524 // update method flags.
2525 ReverifyClasses(holder);
Alex Lighta01de592016-11-15 10:43:06 -08002526 return OK;
2527}
2528
Alex Lightb1eebde2019-10-22 16:30:47 +00002529void Redefiner::ReverifyClasses(RedefinitionDataHolder& holder) {
Alex Lightb1eebde2019-10-22 16:30:47 +00002530 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
2531 data.GetRedefinition().ReverifyClass(data);
2532 }
2533}
2534
2535void Redefiner::ClassRedefinition::ReverifyClass(const RedefinitionDataIter &cur_data) {
2536 if (!needs_reverify_) {
2537 return;
2538 }
2539 VLOG(plugin) << "Reverifying " << class_sig_ << " due to soft failures";
2540 std::string error;
2541 // TODO Make verification log level lower
2542 art::verifier::FailureKind failure =
2543 art::verifier::ClassVerifier::ReverifyClass(driver_->self_,
2544 cur_data.GetMirrorClass(),
2545 /*log_level=*/
2546 art::verifier::HardFailLogMode::kLogWarning,
2547 /*api_level=*/
2548 art::Runtime::Current()->GetTargetSdkVersion(),
2549 &error);
2550 CHECK_NE(failure, art::verifier::FailureKind::kHardFailure);
2551}
2552
Alex Light0e692732017-01-10 15:00:05 -08002553void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002554 const art::dex::ClassDef& class_def) {
Alex Light0e692732017-01-10 15:00:05 -08002555 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08002556 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002557 const art::dex::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08002558 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08002559 // Update methods.
Alex Light00e475c2017-07-19 16:36:23 -07002560 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002561 const art::dex::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
Alex Lighta01de592016-11-15 10:43:06 -08002562 art::dex::TypeIndex method_return_idx =
2563 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
2564 const auto* old_type_list = method.GetParameterTypeList();
2565 std::vector<art::dex::TypeIndex> new_type_list;
2566 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
2567 new_type_list.push_back(
2568 dex_file_->GetIndexForTypeId(
2569 *dex_file_->FindTypeId(
2570 old_dex_file.GetTypeDescriptor(
2571 old_dex_file.GetTypeId(
2572 old_type_list->GetTypeItem(i).type_idx_)))));
2573 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002574 const art::dex::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx, new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08002575 CHECK(proto_id != nullptr || old_type_list == nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002576 const art::dex::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
2577 *new_name_id,
2578 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08002579 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08002580 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
2581 method.SetDexMethodIndex(dex_method_idx);
2582 linker->SetEntryPointsToInterpreter(&method);
Nicolas Geoffray47171752020-08-31 15:03:20 +01002583 if (method.HasCodeItem()) {
2584 method.SetCodeItem(
2585 dex_file_->GetCodeItem(dex_file_->FindCodeItemOffset(class_def, dex_method_idx)));
2586 }
Alex Light7532d582017-02-13 16:36:06 -08002587 // Clear all the intrinsics related flags.
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +01002588 method.SetNotIntrinsic();
Alex Lighta01de592016-11-15 10:43:06 -08002589 }
Alex Light200b9d72016-12-15 11:34:13 -08002590}
2591
Alex Light0e692732017-01-10 15:00:05 -08002592void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08002593 // 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;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002597 const art::dex::TypeId* new_declaring_id =
Alex Light200b9d72016-12-15 11:34:13 -08002598 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002599 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());
Alex Light200b9d72016-12-15 11:34:13 -08002601 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002602 const art::dex::FieldId* new_field_id =
Alex Light200b9d72016-12-15 11:34:13 -08002603 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
2604 CHECK(new_field_id != nullptr);
Alex Light163652e2020-01-08 15:18:25 -08002605 uint32_t new_field_index = dex_file_->GetIndexForFieldId(*new_field_id);
Alex Light200b9d72016-12-15 11:34:13 -08002606 // We only need to update the index since the other data in the ArtField cannot be updated.
Alex Light163652e2020-01-08 15:18:25 -08002607 field.SetDexFieldIndex(new_field_index);
Alex Light200b9d72016-12-15 11:34:13 -08002608 }
2609 }
Alex Light200b9d72016-12-15 11:34:13 -08002610}
2611
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002612void 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) {
Alex Light270db1c2019-12-03 12:20:01 +00002616 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 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002638 }
2639}
2640
Alex Light986914b2019-11-19 01:12:25 +00002641static 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
2673static 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
2695static 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
2723static 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
2736static 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
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002755void Redefiner::ClassRedefinition::UpdateClassStructurally(const RedefinitionDataIter& holder) {
Alex Lightfb537082019-12-10 14:38:34 -08002756 DCHECK(holder.IsActuallyStructural());
2757 DCHECK(holder.IsInitialStructural());
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002758 // 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_);
Alex Light16527e82020-06-08 09:21:12 -07002762 art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002763 art::ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Alex Light270db1c2019-12-03 12:20:01 +00002764 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());
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002766 // 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);
Alex Light986914b2019-11-19 01:12:25 +00002770 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());
Alex Light270db1c2019-12-03 12:20:01 +00002774 // 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());
Alex Light986914b2019-11-19 01:12:25 +00002778 // Copy over the static fields of the class and all the instance fields.
Alex Light270db1c2019-12-03 12:20:01 +00002779 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 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002790
Alex Light986914b2019-11-19 01:12:25 +00002791 // Copy and clear the fields of the old-instances.
Alex Light270db1c2019-12-03 12:20:01 +00002792 for (auto [new_instance, old_instance] :
2793 art::ZipLeft(new_instances->Iterate(), old_instances->Iterate())) {
Alex Light986914b2019-11-19 01:12:25 +00002794 CopyAndClearFields(/*is_static=*/false,
2795 new_instance,
2796 new_instance->GetClass(),
2797 old_instance,
2798 old_instance->GetClass());
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002799 }
Alex Light16527e82020-06-08 09:21:12 -07002800 // 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())) {
Alex Light270db1c2019-12-03 12:20:01 +00002802 old_class->SetObsoleteObject();
Alex Light16527e82020-06-08 09:21:12 -07002803 // 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.
Alex Light270db1c2019-12-03 12:20:01 +00002807 for (art::ArtMethod& m : old_class->GetMethods(art::kRuntimePointerSize)) {
Alex Light16527e82020-06-08 09:21:12 -07002808 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 }
Alex Light270db1c2019-12-03 12:20:01 +00002816 m.SetIsObsolete();
Alex Light16527e82020-06-08 09:21:12 -07002817 cl->SetEntryPointsForObsoleteMethod(&m);
Alex Light270db1c2019-12-03 12:20:01 +00002818 if (m.IsInvokable()) {
2819 m.SetDontCompile();
2820 }
2821 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002822 }
Alex Lightc18eba32019-09-24 14:36:27 -07002823 // Update live pointers in ART code.
Alex Light24627892019-11-06 10:28:21 -08002824 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
Alex Lightbf6498e2020-07-21 17:03:26 -07002847 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())) {
Alex Light24627892019-11-06 10:28:21 -08002853 return false;
2854 }
2855 if constexpr (is_method) {
Alex Lightbf6498e2020-07-21 17:03:26 -07002856 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 });
Alex Light24627892019-11-06 10:28:21 -08002867 } 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()) {
Alex Lightbf6498e2020-07-21 17:03:26 -07002874 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 });
Alex Light24627892019-11-06 10:28:21 -08002881 } else {
Alex Lightbf6498e2020-07-21 17:03:26 -07002882 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 });
Alex Light24627892019-11-06 10:28:21 -08002889 }
2890 }
2891 };
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002892 // 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.
Alex Lightc18eba32019-09-24 14:36:27 -07002894 driver_->runtime_->VisitReflectiveTargets(
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002895 [&](art::ArtField* f, const auto& info) REQUIRES(art::Locks::mutator_lock_) {
Alex Light28b6efe2019-11-06 12:49:41 -08002896 DCHECK(f != nullptr) << info;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002897 auto it = field_map.find(f);
Alex Lightbf6498e2020-07-21 17:03:26 -07002898 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()) {
Alex Light24627892019-11-06 10:28:21 -08002903 VLOG(plugin) << "Updating " << info << " object for (field) "
2904 << it->second->PrettyField();
2905 return it->second;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002906 }
Alex Light24627892019-11-06 10:28:21 -08002907 return f;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002908 },
2909 [&](art::ArtMethod* m, const auto& info) REQUIRES(art::Locks::mutator_lock_) {
Alex Light28b6efe2019-11-06 12:49:41 -08002910 DCHECK(m != nullptr) << info;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002911 auto it = method_map.find(m);
Alex Lightbf6498e2020-07-21 17:03:26 -07002912 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()) {
Alex Light24627892019-11-06 10:28:21 -08002917 VLOG(plugin) << "Updating " << info << " object for (method) "
2918 << it->second->PrettyMethod();
2919 return it->second;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002920 }
Alex Light24627892019-11-06 10:28:21 -08002921 return m;
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002922 });
2923
2924 // Force every frame of every thread to deoptimize (any frame might have eg offsets compiled in).
2925 driver_->runtime_->GetInstrumentation()->DeoptimizeAllThreadFrames();
2926
Alex Light986914b2019-11-19 01:12:25 +00002927 std::unordered_map<art::ObjPtr<art::mirror::Object>,
2928 art::ObjPtr<art::mirror::Object>,
2929 art::HashObjPtr> map;
Alex Light270db1c2019-12-03 12:20:01 +00002930 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();
Alex Light986914b2019-11-19 01:12:25 +00002940 }
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);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002946
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.
Alex Light270db1c2019-12-03 12:20:01 +00002949 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 }
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002953
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002954 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
Alex Lightbf6498e2020-07-21 17:03:26 -07002974 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 });
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00002993 }
2994}
2995
2996// Redefines the class in place
2997void 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());
Alex Light6ac57502017-01-19 15:05:06 -08003003 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003004 const art::dex::ClassDef& class_def = dex_file_->GetClassDef(0);
Vladimir Marko5122e6b2017-08-17 16:10:09 +01003005 UpdateMethods(mclass, class_def);
Alex Light007ada22017-01-10 13:33:56 -08003006 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08003007
David Brazdil1a658632018-12-01 17:54:26 +00003008 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
Alex Lighta01de592016-11-15 10:43:06 -08003021 // 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());
Alex Light6ac57502017-01-19 15:05:06 -08003025 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08003026 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Light035105f2018-03-05 17:48:48 -08003027
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 }
Alex Lighta01de592016-11-15 10:43:06 -08003044}
3045
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00003046// Performs final updates to class for redefinition.
3047void Redefiner::ClassRedefinition::UpdateClass(const RedefinitionDataIter& holder) {
Alex Lightfb537082019-12-10 14:38:34 -08003048 CHECK(holder.IsInitialized());
3049 if (holder.IsInitialStructural()) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00003050 UpdateClassStructurally(holder);
Alex Lightfb537082019-12-10 14:38:34 -08003051 } else if (!holder.IsActuallyStructural()) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00003052 UpdateClassInPlace(holder);
3053 }
Alex Lightc2d0c962019-10-23 14:14:25 -07003054 UpdateClassCommon(holder);
3055}
3056
3057void 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);
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00003073}
3074
Alex Light1e3926a2017-04-07 10:38:06 -07003075// Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
3076// obsolete methods).
3077void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
3078 const RedefinitionDataIter* cur_data) {
Alex Lightfb537082019-12-10 14:38:34 -08003079 if (cur_data->IsActuallyStructural()) {
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00003080 // We didn't touch these in this case.
3081 return;
3082 }
Vladimir Markod93e3742018-07-18 10:58:13 +01003083 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();
Alex Light70713df2017-04-18 13:03:31 -07003087 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
Alex Light1e3926a2017-04-07 10:38:06 -07003088 int32_t expected_length =
3089 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
3090 // Check to make sure we are only undoing this one.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00003091 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()) {
Alex Light70713df2017-04-18 13:03:31 -07003095 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) {
Alex Light1e3926a2017-04-07 10:38:06 -07003101 // 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
Alex Lighta01de592016-11-15 10:43:06 -08003111// This function does all (java) allocations we need to do for the Class being redefined.
3112// TODO Change this name maybe?
Alex Light1e3926a2017-04-07 10:38:06 -07003113bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
3114 /*out*/RedefinitionDataIter* cur_data) {
Alex Light0e692732017-01-10 15:00:05 -08003115 art::StackHandleScope<2> hs(driver_->self_);
3116 art::Handle<art::mirror::Class> klass(hs.NewHandle(
3117 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003118 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08003119 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
3120 return false;
3121 }
3122 // Allocate the classExt
Vladimir Marko3068d582019-05-28 16:39:29 +01003123 art::Handle<art::mirror::ClassExt> ext =
3124 hs.NewHandle(art::mirror::Class::EnsureExtDataPresent(klass, driver_->self_));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003125 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08003126 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08003127 driver_->self_->AssertPendingOOMException();
3128 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08003129 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
3130 return false;
3131 }
Alex Lightfb537082019-12-10 14:38:34 -08003132 if (!cur_data->IsActuallyStructural()) {
3133 CHECK(!IsStructuralRedefinition());
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00003134 // 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 }
Alex Lighta01de592016-11-15 10:43:06 -08003149 }
3150 return true;
3151}
3152
3153} // namespace openjdkjvmti