blob: e720317e4f5d21d6b8daf70eb9beac8f4815ac0b [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
Alex Lighte7a33542019-04-10 14:22:49 -070034#include <iterator>
Alex Lighta01de592016-11-15 10:43:06 -080035#include <limits>
Vladimir Markoeb37ba52019-02-05 14:10:38 +000036#include <string_view>
Alex Lighte7a33542019-04-10 14:22:49 -070037#include <unordered_map>
Alex Lighta01de592016-11-15 10:43:06 -080038
Andreas Gampe57943812017-12-06 21:39:13 -080039#include <android-base/logging.h>
40#include <android-base/stringprintf.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080041
Andreas Gampea1d2f952017-04-20 22:53:58 -070042#include "art_field-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080043#include "art_jvmti.h"
Steven Morelande431e272017-07-18 16:53:49 -070044#include "art_method-inl.h"
Vladimir Markoe1993c72017-06-14 17:01:38 +010045#include "base/array_ref.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080046#include "class_linker-inl.h"
Vladimir Markob4eb1b12018-05-24 11:09:38 +010047#include "class_root.h"
Alex Light5643caf2017-02-08 11:39:07 -080048#include "debugger.h"
David Sehr013fd802018-01-11 22:55:24 -080049#include "dex/art_dex_file_loader.h"
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -070050#include "dex/class_accessor-inl.h"
David Sehr9e734c72018-01-04 17:56:19 -080051#include "dex/dex_file.h"
52#include "dex/dex_file_loader.h"
53#include "dex/dex_file_types.h"
Andreas Gampead1aa632019-01-02 10:30:54 -080054#include "dex/signature-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080055#include "events-inl.h"
56#include "gc/allocation_listener.h"
Alex Light6abd5392017-01-05 17:53:00 -080057#include "gc/heap.h"
Alex Lighta01de592016-11-15 10:43:06 -080058#include "instrumentation.h"
Alex Light07f06212017-06-01 14:01:43 -070059#include "intern_table.h"
Alex Light5643caf2017-02-08 11:39:07 -080060#include "jdwp/jdwp.h"
61#include "jdwp/jdwp_constants.h"
62#include "jdwp/jdwp_event.h"
63#include "jdwp/object_registry.h"
Alex Lightdba61482016-12-21 08:20:29 -080064#include "jit/jit.h"
65#include "jit/jit_code_cache.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010066#include "jni/jni_env_ext-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080067#include "jvmti_allocator.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010068#include "linear_alloc.h"
Andreas Gampe8e0f0432018-10-24 13:38:03 -070069#include "mirror/array-alloc-inl.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070070#include "mirror/class-alloc-inl.h"
Alex Light6161f132017-01-25 10:30:20 -080071#include "mirror/class-inl.h"
Vladimir Markobb206de2019-03-28 10:30:32 +000072#include "mirror/class_ext-inl.h"
Alex Lighta01de592016-11-15 10:43:06 -080073#include "mirror/object.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -070074#include "mirror/object_array-alloc-inl.h"
75#include "mirror/object_array-inl.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070076#include "nativehelper/scoped_local_ref.h"
Alex Lighte77b48b2017-02-22 11:08:06 -080077#include "non_debuggable_classes.h"
Alex Lighta01de592016-11-15 10:43:06 -080078#include "object_lock.h"
79#include "runtime.h"
Vladimir Marko5924a4a2018-05-29 17:40:41 +010080#include "stack.h"
81#include "thread_list.h"
Alex Lighta26e3492017-06-27 17:55:37 -070082#include "ti_breakpoint.h"
Alex Lighteb98b082017-01-25 13:02:32 -080083#include "ti_class_loader.h"
Alex Light0e692732017-01-10 15:00:05 -080084#include "transform.h"
Andreas Gampea43ba3d2019-03-13 15:49:20 -070085#include "verifier/class_verifier.h"
Andreas Gampe6d7abbd2017-04-24 13:19:09 -070086#include "verifier/verifier_enums.h"
Alex Lighta01de592016-11-15 10:43:06 -080087
88namespace openjdkjvmti {
89
Andreas Gampe46ee31b2016-12-14 10:11:49 -080090using android::base::StringPrintf;
91
Alex Lighteee0bd42017-02-14 15:31:45 +000092// A helper that fills in a classes obsolete_methods_ and obsolete_dex_caches_ classExt fields as
93// they are created. This ensures that we can always call any method of an obsolete ArtMethod object
94// almost as soon as they are created since the GetObsoleteDexCache method will succeed.
95class ObsoleteMap {
96 public:
Alex Lighte7a33542019-04-10 14:22:49 -070097 art::ArtMethod* FindObsoleteVersion(art::ArtMethod* original) const
Alex Lighteee0bd42017-02-14 15:31:45 +000098 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
99 auto method_pair = id_map_.find(original);
100 if (method_pair != id_map_.end()) {
101 art::ArtMethod* res = obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
102 method_pair->second, art::kRuntimePointerSize);
103 DCHECK(res != nullptr);
Alex Lighteee0bd42017-02-14 15:31:45 +0000104 return res;
105 } else {
106 return nullptr;
107 }
108 }
109
110 void RecordObsolete(art::ArtMethod* original, art::ArtMethod* obsolete)
111 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
112 DCHECK(original != nullptr);
113 DCHECK(obsolete != nullptr);
114 int32_t slot = next_free_slot_++;
115 DCHECK_LT(slot, obsolete_methods_->GetLength());
116 DCHECK(nullptr ==
117 obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(slot, art::kRuntimePointerSize));
118 DCHECK(nullptr == obsolete_dex_caches_->Get(slot));
119 obsolete_methods_->SetElementPtrSize(slot, obsolete, art::kRuntimePointerSize);
120 obsolete_dex_caches_->Set(slot, original_dex_cache_);
121 id_map_.insert({original, slot});
122 }
123
124 ObsoleteMap(art::ObjPtr<art::mirror::PointerArray> obsolete_methods,
125 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches,
126 art::ObjPtr<art::mirror::DexCache> original_dex_cache)
127 : next_free_slot_(0),
128 obsolete_methods_(obsolete_methods),
129 obsolete_dex_caches_(obsolete_dex_caches),
130 original_dex_cache_(original_dex_cache) {
131 // Figure out where the first unused slot in the obsolete_methods_ array is.
132 while (obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
133 next_free_slot_, art::kRuntimePointerSize) != nullptr) {
134 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) != nullptr);
135 next_free_slot_++;
136 }
137 // Sanity check that the same slot in obsolete_dex_caches_ is free.
138 DCHECK(obsolete_dex_caches_->Get(next_free_slot_) == nullptr);
139 }
140
Alex Lighte7a33542019-04-10 14:22:49 -0700141 struct ObsoleteMethodPair {
142 art::ArtMethod* old_method;
143 art::ArtMethod* obsolete_method;
144 };
145
Vladimir Markoeab02482019-05-09 10:28:17 +0100146 class ObsoleteMapIter {
Alex Lighte7a33542019-04-10 14:22:49 -0700147 public:
Vladimir Markoeab02482019-05-09 10:28:17 +0100148 using iterator_category = std::forward_iterator_tag;
149 using value_type = ObsoleteMethodPair;
150 using difference_type = ptrdiff_t;
151 using pointer = void; // Unsupported.
152 using reference = void; // Unsupported.
153
Alex Lighte7a33542019-04-10 14:22:49 -0700154 ObsoleteMethodPair operator*() const
155 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
Vladimir Markoeab02482019-05-09 10:28:17 +0100156 art::ArtMethod* obsolete = map_->obsolete_methods_->GetElementPtrSize<art::ArtMethod*>(
157 iter_->second, art::kRuntimePointerSize);
Alex Lighte7a33542019-04-10 14:22:49 -0700158 DCHECK(obsolete != nullptr);
159 return { iter_->first, obsolete };
160 }
161
162 bool operator==(ObsoleteMapIter other) const {
163 return map_ == other.map_ && iter_ == other.iter_;
164 }
165
166 bool operator!=(ObsoleteMapIter other) const {
167 return !(*this == other);
168 }
169
Vladimir Markoeab02482019-05-09 10:28:17 +0100170 ObsoleteMapIter operator++(int) {
Alex Lighte7a33542019-04-10 14:22:49 -0700171 ObsoleteMapIter retval = *this;
172 ++(*this);
173 return retval;
174 }
175
Vladimir Markoeab02482019-05-09 10:28:17 +0100176 ObsoleteMapIter operator++() {
Alex Lighte7a33542019-04-10 14:22:49 -0700177 ++iter_;
178 return *this;
179 }
180
181 private:
182 ObsoleteMapIter(const ObsoleteMap* map,
183 std::unordered_map<art::ArtMethod*, int32_t>::const_iterator iter)
184 : map_(map), iter_(iter) {}
185
186 const ObsoleteMap* map_;
Vladimir Markoeab02482019-05-09 10:28:17 +0100187 std::unordered_map<art::ArtMethod*, int32_t>::const_iterator iter_;
Alex Lighte7a33542019-04-10 14:22:49 -0700188
189 friend class ObsoleteMap;
190 };
191
192 ObsoleteMapIter end() const {
193 return ObsoleteMapIter(this, id_map_.cend());
194 }
195
196 ObsoleteMapIter begin() const {
197 return ObsoleteMapIter(this, id_map_.cbegin());
198 }
199
Alex Lighteee0bd42017-02-14 15:31:45 +0000200 private:
201 int32_t next_free_slot_;
202 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
203 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
204 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
205 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
206 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
207 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
208};
209
Alex Lightdba61482016-12-21 08:20:29 -0800210// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
211// some basic sanity checks that the obsolete method is sane.
212class ObsoleteMethodStackVisitor : public art::StackVisitor {
213 protected:
214 ObsoleteMethodStackVisitor(
215 art::Thread* thread,
216 art::LinearAlloc* allocator,
217 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000218 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800219 : StackVisitor(thread,
Andreas Gampe6e897762018-10-16 13:09:32 -0700220 /*context=*/nullptr,
Alex Lightdba61482016-12-21 08:20:29 -0800221 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
222 allocator_(allocator),
223 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800224 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800225
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100226 ~ObsoleteMethodStackVisitor() override {}
Alex Lightdba61482016-12-21 08:20:29 -0800227
228 public:
229 // Returns true if we successfully installed obsolete methods on this thread, filling
230 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
231 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800232 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800233 art::Thread* thread,
234 art::LinearAlloc* allocator,
235 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000236 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800237 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800238 ObsoleteMethodStackVisitor visitor(thread,
239 allocator,
240 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800241 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800242 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800243 }
244
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100245 bool VisitFrame() override REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000246 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800247 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800248 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800249 // We cannot ensure that the right dex file is used in inlined frames so we don't support
250 // redefining them.
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000251 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition: "
252 << old_method->PrettyMethod() << " is inlined into "
253 << GetOuterMethod()->PrettyMethod();
Alex Lighteee0bd42017-02-14 15:31:45 +0000254 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
255 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800256 // Create a new Obsolete Method and put it in the list.
257 art::Runtime* runtime = art::Runtime::Current();
258 art::ClassLinker* cl = runtime->GetClassLinker();
259 auto ptr_size = cl->GetImagePointerSize();
260 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800261 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800262 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
263 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800264 new_obsolete_method = new (method_storage) art::ArtMethod();
265 new_obsolete_method->CopyFrom(old_method, ptr_size);
266 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
267 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800268 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700269 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000270 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800271 }
272 DCHECK(new_obsolete_method != nullptr);
273 SetMethod(new_obsolete_method);
274 }
275 return true;
276 }
277
278 private:
279 // The linear allocator we should use to make new methods.
280 art::LinearAlloc* allocator_;
281 // The set of all methods which could be obsoleted.
282 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
283 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000284 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
285 // the redefined classes ClassExt as it is filled.
286 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800287};
288
Alex Lighte4a88632017-01-10 07:41:24 -0800289jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
290 jclass klass,
291 jboolean* is_redefinable) {
Alex Lighte4a88632017-01-10 07:41:24 -0800292 art::Thread* self = art::Thread::Current();
293 art::ScopedObjectAccess soa(self);
294 art::StackHandleScope<1> hs(self);
295 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
Alex Light413a8ad2019-02-14 10:19:44 -0800296 if (obj.IsNull() || !obj->IsClass()) {
Alex Lighte4a88632017-01-10 07:41:24 -0800297 return ERR(INVALID_CLASS);
298 }
299 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
300 std::string err_unused;
301 *is_redefinable =
Alex Light9e7859c2018-04-05 13:49:43 -0700302 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) != ERR(UNMODIFIABLE_CLASS)
303 ? JNI_TRUE : JNI_FALSE;
Alex Lighte4a88632017-01-10 07:41:24 -0800304 return OK;
305}
306
Alex Light9e7859c2018-04-05 13:49:43 -0700307jvmtiError Redefiner::GetClassRedefinitionError(jclass klass, /*out*/std::string* error_msg) {
308 art::Thread* self = art::Thread::Current();
309 art::ScopedObjectAccess soa(self);
310 art::StackHandleScope<1> hs(self);
311 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
Alex Light413a8ad2019-02-14 10:19:44 -0800312 if (obj.IsNull() || !obj->IsClass()) {
Alex Light9e7859c2018-04-05 13:49:43 -0700313 return ERR(INVALID_CLASS);
314 }
315 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
316 return Redefiner::GetClassRedefinitionError(h_klass, error_msg);
317}
318
Alex Lighte4a88632017-01-10 07:41:24 -0800319jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
320 /*out*/std::string* error_msg) {
Alex Light9e7859c2018-04-05 13:49:43 -0700321 if (!klass->IsResolved()) {
322 // It's only a problem to try to retransform/redefine a unprepared class if it's happening on
323 // the same thread as the class-linking process. If it's on another thread we will be able to
324 // wait for the preparation to finish and continue from there.
325 if (klass->GetLockOwnerThreadId() == art::Thread::Current()->GetThreadId()) {
326 *error_msg = "Modification of class " + klass->PrettyClass() +
327 " from within the classes ClassLoad callback is not supported to prevent deadlocks." +
328 " Please use ClassFileLoadHook directly instead.";
329 return ERR(INTERNAL);
330 } else {
331 LOG(WARNING) << klass->PrettyClass() << " is not yet resolved. Attempting to transform "
332 << "it could cause arbitrary length waits as the class is being resolved.";
333 }
334 }
Alex Lighte4a88632017-01-10 07:41:24 -0800335 if (klass->IsPrimitive()) {
336 *error_msg = "Modification of primitive classes is not supported";
337 return ERR(UNMODIFIABLE_CLASS);
338 } else if (klass->IsInterface()) {
339 *error_msg = "Modification of Interface classes is currently not supported";
340 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800341 } else if (klass->IsStringClass()) {
342 *error_msg = "Modification of String class is not supported";
343 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800344 } else if (klass->IsArrayClass()) {
345 *error_msg = "Modification of Array classes is not supported";
346 return ERR(UNMODIFIABLE_CLASS);
347 } else if (klass->IsProxyClass()) {
348 *error_msg = "Modification of proxy classes is not supported";
349 return ERR(UNMODIFIABLE_CLASS);
350 }
351
Alex Lighte77b48b2017-02-22 11:08:06 -0800352 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
353 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
354 *error_msg = "Class might have stack frames that cannot be made obsolete";
355 return ERR(UNMODIFIABLE_CLASS);
356 }
357 }
358
Alex Lighte4a88632017-01-10 07:41:24 -0800359 return OK;
360}
361
Alex Lighta01de592016-11-15 10:43:06 -0800362// Moves dex data to an anonymous, read-only mmap'd region.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100363art::MemMap Redefiner::MoveDataToMemMap(const std::string& original_location,
364 art::ArrayRef<const unsigned char> data,
365 std::string* error_msg) {
366 art::MemMap map = art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800367 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lightb7354d52017-03-30 15:17:01 -0700368 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800369 PROT_READ|PROT_WRITE,
Andreas Gampe6e897762018-10-16 13:09:32 -0700370 /*low_4gb=*/ false,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100371 error_msg);
372 if (LIKELY(map.IsValid())) {
373 memcpy(map.Begin(), data.data(), data.size());
374 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
375 // programs from corrupting it.
376 map.Protect(PROT_READ);
Alex Lighta01de592016-11-15 10:43:06 -0800377 }
Alex Lighta01de592016-11-15 10:43:06 -0800378 return map;
379}
380
Alex Lighta7e38d82017-01-19 14:57:28 -0800381Redefiner::ClassRedefinition::ClassRedefinition(
382 Redefiner* driver,
383 jclass klass,
384 const art::DexFile* redefined_dex_file,
385 const char* class_sig,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100386 art::ArrayRef<const unsigned char> orig_dex_file) :
Alex Lighta7e38d82017-01-19 14:57:28 -0800387 driver_(driver),
388 klass_(klass),
389 dex_file_(redefined_dex_file),
390 class_sig_(class_sig),
391 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800392 GetMirrorClass()->MonitorEnter(driver_->self_);
393}
394
395Redefiner::ClassRedefinition::~ClassRedefinition() {
396 if (driver_ != nullptr) {
397 GetMirrorClass()->MonitorExit(driver_->self_);
398 }
399}
400
Alex Light0e692732017-01-10 15:00:05 -0800401jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800402 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800403 art::Runtime* runtime,
404 art::Thread* self,
405 jint class_count,
406 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800407 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800408 if (env == nullptr) {
409 *error_msg = "env was null!";
410 return ERR(INVALID_ENVIRONMENT);
411 } else if (class_count < 0) {
412 *error_msg = "class_count was less then 0";
413 return ERR(ILLEGAL_ARGUMENT);
414 } else if (class_count == 0) {
415 // We don't actually need to do anything. Just return OK.
416 return OK;
417 } else if (definitions == nullptr) {
418 *error_msg = "null definitions!";
419 return ERR(NULL_POINTER);
420 }
Alex Light6ac57502017-01-19 15:05:06 -0800421 std::vector<ArtClassDefinition> def_vector;
422 def_vector.reserve(class_count);
423 for (jint i = 0; i < class_count; i++) {
Alex Light9e7859c2018-04-05 13:49:43 -0700424 jvmtiError res = Redefiner::GetClassRedefinitionError(definitions[i].klass, error_msg);
Alex Lightce6ee702017-03-06 15:46:43 -0800425 if (res != OK) {
426 return res;
Alex Lightce6ee702017-03-06 15:46:43 -0800427 }
Alex Light6ac57502017-01-19 15:05:06 -0800428 ArtClassDefinition def;
Alex Light64e4c142018-01-30 13:46:37 -0800429 res = def.Init(self, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800430 if (res != OK) {
431 return res;
432 }
433 def_vector.push_back(std::move(def));
434 }
435 // Call all the transformation events.
Alex Light64e4c142018-01-30 13:46:37 -0800436 jvmtiError res = Transformer::RetransformClassesDirect(event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800437 self,
438 &def_vector);
439 if (res != OK) {
440 // Something went wrong with transformation!
441 return res;
442 }
443 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
444}
445
446jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
447 art::Runtime* runtime,
448 art::Thread* self,
449 const std::vector<ArtClassDefinition>& definitions,
450 std::string* error_msg) {
451 DCHECK(env != nullptr);
452 if (definitions.size() == 0) {
453 // We don't actually need to do anything. Just return OK.
454 return OK;
455 }
Alex Light0e692732017-01-10 15:00:05 -0800456 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
457 // are going to redefine.
458 art::jit::ScopedJitSuspend suspend_jit;
459 // Get shared mutator lock so we can lock all the classes.
460 art::ScopedObjectAccess soa(self);
Alex Lighta26e3492017-06-27 17:55:37 -0700461 Redefiner r(env, runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800462 for (const ArtClassDefinition& def : definitions) {
463 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700464 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800465 jvmtiError res = r.AddRedefinition(env, def);
466 if (res != OK) {
467 return res;
468 }
Alex Light0e692732017-01-10 15:00:05 -0800469 }
470 }
471 return r.Run();
472}
473
Alex Light6ac57502017-01-19 15:05:06 -0800474jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800475 std::string original_dex_location;
476 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700477 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800478 *error_msg_ = "Unable to get original dex file location!";
479 return ret;
480 }
Alex Light52a2db52017-01-19 23:00:21 +0000481 char* generic_ptr_unused = nullptr;
482 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700483 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800484 *error_msg_ = "Unable to get class signature!";
485 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000486 }
Andreas Gampe54711412017-02-21 12:41:43 -0800487 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
488 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100489 art::MemMap map = MoveDataToMemMap(original_dex_location, def.GetDexData(), error_msg_);
Alex Light6ac57502017-01-19 15:05:06 -0800490 std::ostringstream os;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100491 if (!map.IsValid()) {
Alex Lightb7354d52017-03-30 15:17:01 -0700492 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800493 << "in dex file " << original_dex_location << " because: " << *error_msg_;
494 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800495 return ERR(OUT_OF_MEMORY);
496 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100497 if (map.Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800498 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800499 return ERR(INVALID_CLASS_FORMAT);
500 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100501 std::string name = map.GetName();
502 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
David Sehr013fd802018-01-11 22:55:24 -0800503 const art::ArtDexFileLoader dex_file_loader;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100504 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(name,
David Sehr013fd802018-01-11 22:55:24 -0800505 checksum,
506 std::move(map),
Andreas Gampe6e897762018-10-16 13:09:32 -0700507 /*verify=*/true,
508 /*verify_checksum=*/true,
David Sehr013fd802018-01-11 22:55:24 -0800509 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800510 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700511 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800512 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800513 return ERR(INVALID_CLASS_FORMAT);
514 }
Alex Light0e692732017-01-10 15:00:05 -0800515 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800516 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700517 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800518 dex_file.release(),
519 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700520 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800521 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800522}
523
Vladimir Marko4617d582019-03-28 13:48:31 +0000524art::ObjPtr<art::mirror::Class> Redefiner::ClassRedefinition::GetMirrorClass() {
Alex Light0e692732017-01-10 15:00:05 -0800525 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800526}
527
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000528art::ObjPtr<art::mirror::ClassLoader> Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800529 return GetMirrorClass()->GetClassLoader();
530}
531
Alex Light0e692732017-01-10 15:00:05 -0800532art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
533 art::Handle<art::mirror::ClassLoader> loader) {
Alex Light07f06212017-06-01 14:01:43 -0700534 art::StackHandleScope<2> hs(driver_->self_);
535 art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
536 art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
537 art::ObjPtr<art::mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100538 art::GetClassRoot<art::mirror::DexCache>(cl)->AllocObject(driver_->self_))));
Alex Light07f06212017-06-01 14:01:43 -0700539 if (cache.IsNull()) {
540 driver_->self_->AssertPendingOOMException();
541 return nullptr;
542 }
543 art::Handle<art::mirror::String> location(hs.NewHandle(
544 cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
545 if (location.IsNull()) {
546 driver_->self_->AssertPendingOOMException();
547 return nullptr;
548 }
549 art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
550 art::mirror::DexCache::InitializeDexCache(driver_->self_,
551 cache.Get(),
552 location.Get(),
553 dex_file_.get(),
554 loader.IsNull() ? driver_->runtime_->GetLinearAlloc()
555 : loader->GetAllocator(),
556 art::kRuntimePointerSize);
557 return cache.Get();
Alex Lighta01de592016-11-15 10:43:06 -0800558}
559
Alex Light0e692732017-01-10 15:00:05 -0800560void Redefiner::RecordFailure(jvmtiError result,
561 const std::string& class_sig,
562 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800563 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800564 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800565 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800566 result_ = result;
567}
568
Alex Light2f814aa2017-03-24 15:21:34 +0000569art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800570 // If we have been specifically given a new set of bytes use that
571 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800572 return art::mirror::ByteArray::AllocateAndFill(
573 driver_->self_,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100574 reinterpret_cast<const signed char*>(original_dex_file_.data()),
Vladimir Markobcf17522018-06-01 13:14:32 +0100575 original_dex_file_.size()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800576 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800577
578 // See if we already have one set.
579 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
580 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000581 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
582 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800583 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000584 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800585 }
Alex Lighta01de592016-11-15 10:43:06 -0800586 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800587
Alex Light2f814aa2017-03-24 15:21:34 +0000588 // return the current dex_cache which has the dex file in it.
589 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800590 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000591 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800592 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
593 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800594 }
Alex Light2f814aa2017-03-24 15:21:34 +0000595 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800596}
597
Alex Lightdba61482016-12-21 08:20:29 -0800598struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000599 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800600 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800601 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800602
Alex Lighteee0bd42017-02-14 15:31:45 +0000603 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
604 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800605};
606
Alex Lightdba61482016-12-21 08:20:29 -0800607void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
608 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800609 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
610 data->allocator,
611 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000612 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800613}
614
615// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
616// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800617// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
Vladimir Markod93e3742018-07-18 10:58:13 +0100618void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(
619 art::ObjPtr<art::mirror::Class> art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800620 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
Vladimir Markod93e3742018-07-18 10:58:13 +0100621 art::ObjPtr<art::mirror::ClassExt> ext = art_klass->GetExtData();
Alex Lightdba61482016-12-21 08:20:29 -0800622 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800623 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000624 // This holds pointers to the obsolete methods map fields which are updated as needed.
625 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
626 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800627 // Add all the declared methods to the map
628 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800629 if (m.IsIntrinsic()) {
630 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
631 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
632 << "methods that have already been compiled.";
633 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000634 // It is possible to simply filter out some methods where they cannot really become obsolete,
635 // such as native methods and keep their original (possibly optimized) implementations. We don't
636 // do this, however, since we would need to mark these functions (still in the classes
637 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
638 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
639 // error checking from the interpreter which ensure we don't try to start executing obsolete
640 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000641 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800642 }
643 {
Alex Light0e692732017-01-10 15:00:05 -0800644 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800645 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
646 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Vladimir Markoeab02482019-05-09 10:28:17 +0100647 // After we've done walking all threads' stacks and updating method pointers on them,
648 // update JIT data structures (used by the stack walk above) to point to the new methods.
Alex Lighte7a33542019-04-10 14:22:49 -0700649 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
650 if (jit != nullptr) {
651 for (const ObsoleteMap::ObsoleteMethodPair& it : *ctx.obsolete_map) {
652 // Notify the JIT we are making this obsolete method. It will update the jit's internal
653 // structures to keep track of the new obsolete method.
654 jit->GetCodeCache()->MoveObsoleteMethod(it.old_method, it.obsolete_method);
655 }
656 }
Alex Lightdba61482016-12-21 08:20:29 -0800657 }
Alex Lightdba61482016-12-21 08:20:29 -0800658}
659
Alex Light6161f132017-01-25 10:30:20 -0800660// Try and get the declared method. First try to get a virtual method then a direct method if that's
661// not found.
662static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
Vladimir Markoeb37ba52019-02-05 14:10:38 +0000663 std::string_view name,
Alex Light6161f132017-01-25 10:30:20 -0800664 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markoba118822017-06-12 15:41:56 +0100665 DCHECK(!klass->IsProxyClass());
666 for (art::ArtMethod& m : klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize)) {
667 if (m.GetName() == name && m.GetSignature() == sig) {
668 return &m;
669 }
Alex Light6161f132017-01-25 10:30:20 -0800670 }
Vladimir Markoba118822017-06-12 15:41:56 +0100671 return nullptr;
Alex Light6161f132017-01-25 10:30:20 -0800672}
673
674bool Redefiner::ClassRedefinition::CheckSameMethods() {
675 art::StackHandleScope<1> hs(driver_->self_);
676 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
677 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
678
Alex Light6161f132017-01-25 10:30:20 -0800679 // Make sure we have the same number of methods.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700680 art::ClassAccessor accessor(*dex_file_, dex_file_->GetClassDef(0));
681 uint32_t num_new_method = accessor.NumMethods();
Alex Light6161f132017-01-25 10:30:20 -0800682 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
683 if (num_new_method != num_old_method) {
684 bool bigger = num_new_method > num_old_method;
685 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
686 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
687 StringPrintf("Total number of declared methods changed from %d to %d",
688 num_old_method, num_new_method));
689 return false;
690 }
691
692 // Skip all of the fields. We should have already checked this.
Alex Light6161f132017-01-25 10:30:20 -0800693 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
694 // files have the same number of methods, which means there must be an equal amount of additions
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700695 // and removals. We should have already checked the fields.
696 for (const art::ClassAccessor::Method& method : accessor.GetMethods()) {
Alex Light6161f132017-01-25 10:30:20 -0800697 // Get the data on the method we are searching for
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800698 const art::dex::MethodId& new_method_id = dex_file_->GetMethodId(method.GetIndex());
Alex Light6161f132017-01-25 10:30:20 -0800699 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
700 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
701 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
702 // If we got past the check for the same number of methods above that means there must be at
703 // least one added and one removed method. We will return the ADDED failure message since it is
704 // easier to get a useful error report for it.
705 if (old_method == nullptr) {
706 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
707 StringPrintf("Unknown method '%s' (sig: %s) was added!",
708 new_method_name,
709 new_method_signature.ToString().c_str()));
710 return false;
711 }
712 // Since direct methods have different flags than virtual ones (specifically direct methods must
713 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
714 // virtual to direct.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700715 uint32_t new_flags = method.GetAccessFlags();
Vladimir Markob0a6aee2017-10-27 10:34:04 +0100716 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
Alex Light6161f132017-01-25 10:30:20 -0800717 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
718 StringPrintf("method '%s' (sig: %s) had different access flags",
719 new_method_name,
720 new_method_signature.ToString().c_str()));
721 return false;
722 }
723 }
724 return true;
725}
726
727bool Redefiner::ClassRedefinition::CheckSameFields() {
728 art::StackHandleScope<1> hs(driver_->self_);
729 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
730 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700731 art::ClassAccessor new_accessor(*dex_file_, dex_file_->GetClassDef(0));
732
Alex Light6161f132017-01-25 10:30:20 -0800733 const art::DexFile& old_dex_file = h_klass->GetDexFile();
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700734 art::ClassAccessor old_accessor(old_dex_file, *h_klass->GetClassDef());
Alex Light6161f132017-01-25 10:30:20 -0800735 // Instance and static fields can be differentiated by their flags so no need to check them
736 // separately.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700737 auto old_fields = old_accessor.GetFields();
738 auto old_iter = old_fields.begin();
739 for (const art::ClassAccessor::Field& new_field : new_accessor.GetFields()) {
Alex Light6161f132017-01-25 10:30:20 -0800740 // Get the data on the method we are searching for
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800741 const art::dex::FieldId& new_field_id = dex_file_->GetFieldId(new_field.GetIndex());
Alex Light6161f132017-01-25 10:30:20 -0800742 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
743 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
744
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700745 if (old_iter == old_fields.end()) {
Alex Light6161f132017-01-25 10:30:20 -0800746 // We are missing the old version of this method!
747 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
748 StringPrintf("Unknown field '%s' (type: %s) added!",
749 new_field_name,
750 new_field_type));
751 return false;
752 }
753
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800754 const art::dex::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter->GetIndex());
Alex Light6161f132017-01-25 10:30:20 -0800755 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
756 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
757
758 // Check name and type.
759 if (strcmp(old_field_name, new_field_name) != 0 ||
760 strcmp(old_field_type, new_field_type) != 0) {
761 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
762 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
763 old_field_name,
764 old_field_type,
765 new_field_name,
766 new_field_type));
767 return false;
768 }
769
770 // Since static fields have different flags than instance ones (specifically static fields must
771 // have the kAccStatic flag) we can tell if a field changes from static to instance.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700772 if (new_field.GetAccessFlags() != old_iter->GetAccessFlags()) {
Alex Light6161f132017-01-25 10:30:20 -0800773 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
774 StringPrintf("Field '%s' (sig: %s) had different access flags",
775 new_field_name,
776 new_field_type));
777 return false;
778 }
779
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700780 ++old_iter;
Alex Light6161f132017-01-25 10:30:20 -0800781 }
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700782 if (old_iter != old_fields.end()) {
Alex Light6161f132017-01-25 10:30:20 -0800783 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
784 StringPrintf("field '%s' (sig: %s) is missing!",
785 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700786 old_iter->GetIndex())),
Alex Light6161f132017-01-25 10:30:20 -0800787 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700788 old_iter->GetIndex()))));
Alex Light6161f132017-01-25 10:30:20 -0800789 return false;
790 }
791 return true;
792}
793
Alex Light0e692732017-01-10 15:00:05 -0800794bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800795 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000796 // Easy check that only 1 class def is present.
797 if (dex_file_->NumClassDefs() != 1) {
798 RecordFailure(ERR(ILLEGAL_ARGUMENT),
799 StringPrintf("Expected 1 class def in dex file but found %d",
800 dex_file_->NumClassDefs()));
801 return false;
802 }
803 // Get the ClassDef from the new DexFile.
804 // Since the dex file has only a single class def the index is always 0.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800805 const art::dex::ClassDef& def = dex_file_->GetClassDef(0);
Alex Light460d1b42017-01-10 15:37:17 +0000806 // Get the class as it is now.
807 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
808
809 // Check the access flags didn't change.
810 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
811 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
812 "Cannot change modifiers of class by redefinition");
813 return false;
814 }
815
816 // Check class name.
817 // These should have been checked by the dexfile verifier on load.
818 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
819 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
820 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
821 if (!current_class->DescriptorEquals(descriptor)) {
822 std::string storage;
823 RecordFailure(ERR(NAMES_DONT_MATCH),
824 StringPrintf("expected file to contain class called '%s' but found '%s'!",
825 current_class->GetDescriptor(&storage),
826 descriptor));
827 return false;
828 }
829 if (current_class->IsObjectClass()) {
830 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
831 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
832 return false;
833 }
834 } else {
835 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
836 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
837 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
838 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
839 return false;
840 }
841 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800842 const art::dex::TypeList* interfaces = dex_file_->GetInterfacesList(def);
Alex Light460d1b42017-01-10 15:37:17 +0000843 if (interfaces == nullptr) {
844 if (current_class->NumDirectInterfaces() != 0) {
845 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
846 return false;
847 }
848 } else {
849 DCHECK(!current_class->IsProxyClass());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800850 const art::dex::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
Alex Light460d1b42017-01-10 15:37:17 +0000851 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
852 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
853 return false;
854 }
855 // The order of interfaces is (barely) meaningful so we error if it changes.
856 const art::DexFile& orig_dex_file = current_class->GetDexFile();
857 for (uint32_t i = 0; i < interfaces->Size(); i++) {
858 if (strcmp(
859 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
860 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
861 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
862 "Interfaces changed or re-ordered");
863 return false;
864 }
865 }
866 }
Alex Light460d1b42017-01-10 15:37:17 +0000867 return true;
868}
869
Alex Light0e692732017-01-10 15:00:05 -0800870bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800871 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800872 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000873
Alex Lighte4a88632017-01-10 07:41:24 -0800874 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
875 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
876 if (res != OK) {
877 RecordFailure(res, err);
878 return false;
879 } else {
880 return true;
881 }
Alex Light460d1b42017-01-10 15:37:17 +0000882}
883
Alex Light0e692732017-01-10 15:00:05 -0800884bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000885 return CheckRedefinable() &&
886 CheckClass() &&
887 CheckSameFields() &&
888 CheckSameMethods();
889}
890
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800891class RedefinitionDataIter;
892
Alex Light0e692732017-01-10 15:00:05 -0800893// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
894// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
895// having to deal with the fact that we need to hold an arbitrary number of references live.
896class RedefinitionDataHolder {
897 public:
898 enum DataSlot : int32_t {
899 kSlotSourceClassLoader = 0,
900 kSlotJavaDexFile = 1,
901 kSlotNewDexFileCookie = 2,
902 kSlotNewDexCache = 3,
903 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800904 kSlotOrigDexFile = 5,
Alex Light1e3926a2017-04-07 10:38:06 -0700905 kSlotOldObsoleteMethods = 6,
906 kSlotOldDexCaches = 7,
Alex Light0e692732017-01-10 15:00:05 -0800907
908 // Must be last one.
Alex Light1e3926a2017-04-07 10:38:06 -0700909 kNumSlots = 8,
Alex Light0e692732017-01-10 15:00:05 -0800910 };
911
912 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
913 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
914 // the passed in handle-scope.
915 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
916 art::Runtime* runtime,
917 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800918 std::vector<Redefiner::ClassRedefinition>* redefinitions)
919 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100920 arr_(hs->NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
921 self,
922 art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Object>>(runtime->GetClassLinker()),
923 redefinitions->size() * kNumSlots))),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800924 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800925
926 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
927 return arr_.IsNull();
928 }
929
Vladimir Markod93e3742018-07-18 10:58:13 +0100930 art::ObjPtr<art::mirror::ClassLoader> GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800931 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100932 return art::ObjPtr<art::mirror::ClassLoader>::DownCast(
933 GetSlot(klass_index, kSlotSourceClassLoader));
Alex Light0e692732017-01-10 15:00:05 -0800934 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100935 art::ObjPtr<art::mirror::Object> GetJavaDexFile(jint klass_index) const
Alex Light8c889d22017-02-06 13:58:27 -0800936 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800937 return GetSlot(klass_index, kSlotJavaDexFile);
938 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100939 art::ObjPtr<art::mirror::LongArray> GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800940 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100941 return art::ObjPtr<art::mirror::LongArray>::DownCast(
942 GetSlot(klass_index, kSlotNewDexFileCookie));
Alex Light0e692732017-01-10 15:00:05 -0800943 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100944 art::ObjPtr<art::mirror::DexCache> GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800945 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100946 return art::ObjPtr<art::mirror::DexCache>::DownCast(GetSlot(klass_index, kSlotNewDexCache));
Alex Light0e692732017-01-10 15:00:05 -0800947 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100948 art::ObjPtr<art::mirror::Class> GetMirrorClass(jint klass_index) const
Alex Light8c889d22017-02-06 13:58:27 -0800949 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100950 return art::ObjPtr<art::mirror::Class>::DownCast(GetSlot(klass_index, kSlotMirrorClass));
Alex Light0e692732017-01-10 15:00:05 -0800951 }
952
Vladimir Markod93e3742018-07-18 10:58:13 +0100953 art::ObjPtr<art::mirror::Object> GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800954 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100955 return art::ObjPtr<art::mirror::Object>::DownCast(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800956 }
957
Vladimir Markod93e3742018-07-18 10:58:13 +0100958 art::ObjPtr<art::mirror::PointerArray> GetOldObsoleteMethods(jint klass_index) const
Alex Light1e3926a2017-04-07 10:38:06 -0700959 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100960 return art::ObjPtr<art::mirror::PointerArray>::DownCast(
Alex Light1e3926a2017-04-07 10:38:06 -0700961 GetSlot(klass_index, kSlotOldObsoleteMethods));
962 }
963
Vladimir Markod93e3742018-07-18 10:58:13 +0100964 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> GetOldDexCaches(
965 jint klass_index) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
966 return art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>>::DownCast(
Alex Light1e3926a2017-04-07 10:38:06 -0700967 GetSlot(klass_index, kSlotOldDexCaches));
968 }
969
Vladimir Markod93e3742018-07-18 10:58:13 +0100970 void SetSourceClassLoader(jint klass_index, art::ObjPtr<art::mirror::ClassLoader> loader)
Alex Light0e692732017-01-10 15:00:05 -0800971 REQUIRES_SHARED(art::Locks::mutator_lock_) {
972 SetSlot(klass_index, kSlotSourceClassLoader, loader);
973 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100974 void SetJavaDexFile(jint klass_index, art::ObjPtr<art::mirror::Object> dexfile)
Alex Light0e692732017-01-10 15:00:05 -0800975 REQUIRES_SHARED(art::Locks::mutator_lock_) {
976 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
977 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100978 void SetNewDexFileCookie(jint klass_index, art::ObjPtr<art::mirror::LongArray> cookie)
Alex Light0e692732017-01-10 15:00:05 -0800979 REQUIRES_SHARED(art::Locks::mutator_lock_) {
980 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
981 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100982 void SetNewDexCache(jint klass_index, art::ObjPtr<art::mirror::DexCache> cache)
Alex Light0e692732017-01-10 15:00:05 -0800983 REQUIRES_SHARED(art::Locks::mutator_lock_) {
984 SetSlot(klass_index, kSlotNewDexCache, cache);
985 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100986 void SetMirrorClass(jint klass_index, art::ObjPtr<art::mirror::Class> klass)
Alex Light0e692732017-01-10 15:00:05 -0800987 REQUIRES_SHARED(art::Locks::mutator_lock_) {
988 SetSlot(klass_index, kSlotMirrorClass, klass);
989 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100990 void SetOriginalDexFile(jint klass_index, art::ObjPtr<art::mirror::Object> bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800991 REQUIRES_SHARED(art::Locks::mutator_lock_) {
992 SetSlot(klass_index, kSlotOrigDexFile, bytes);
993 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100994 void SetOldObsoleteMethods(jint klass_index, art::ObjPtr<art::mirror::PointerArray> methods)
Alex Light1e3926a2017-04-07 10:38:06 -0700995 REQUIRES_SHARED(art::Locks::mutator_lock_) {
996 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
997 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100998 void SetOldDexCaches(jint klass_index,
999 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)
Alex Light1e3926a2017-04-07 10:38:06 -07001000 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1001 SetSlot(klass_index, kSlotOldDexCaches, caches);
1002 }
Alex Light0e692732017-01-10 15:00:05 -08001003
Alex Light8c889d22017-02-06 13:58:27 -08001004 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -08001005 return arr_->GetLength() / kNumSlots;
1006 }
1007
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001008 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
1009 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1010 return redefinitions_;
1011 }
1012
1013 bool operator==(const RedefinitionDataHolder& other) const
1014 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1015 return arr_.Get() == other.arr_.Get();
1016 }
1017
1018 bool operator!=(const RedefinitionDataHolder& other) const
1019 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1020 return !(*this == other);
1021 }
1022
1023 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
1024 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
1025
Alex Light0e692732017-01-10 15:00:05 -08001026 private:
Alex Light8c889d22017-02-06 13:58:27 -08001027 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001028 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -08001029
Vladimir Markod93e3742018-07-18 10:58:13 +01001030 art::ObjPtr<art::mirror::Object> GetSlot(jint klass_index, DataSlot slot) const
1031 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -08001032 DCHECK_LT(klass_index, Length());
1033 return arr_->Get((kNumSlots * klass_index) + slot);
1034 }
1035
1036 void SetSlot(jint klass_index,
1037 DataSlot slot,
1038 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1039 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
1040 DCHECK_LT(klass_index, Length());
1041 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
1042 }
1043
1044 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
1045};
1046
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001047class RedefinitionDataIter {
1048 public:
1049 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
1050
1051 RedefinitionDataIter(const RedefinitionDataIter&) = default;
1052 RedefinitionDataIter(RedefinitionDataIter&&) = default;
1053 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
1054 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
1055
1056 bool operator==(const RedefinitionDataIter& other) const
1057 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1058 return idx_ == other.idx_ && holder_ == other.holder_;
1059 }
1060
1061 bool operator!=(const RedefinitionDataIter& other) const
1062 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1063 return !(*this == other);
1064 }
1065
1066 RedefinitionDataIter operator++() { // Value after modification.
1067 idx_++;
1068 return *this;
1069 }
1070
1071 RedefinitionDataIter operator++(int) {
1072 RedefinitionDataIter temp = *this;
1073 idx_++;
1074 return temp;
1075 }
1076
1077 RedefinitionDataIter operator+(ssize_t delta) const {
1078 RedefinitionDataIter temp = *this;
1079 temp += delta;
1080 return temp;
1081 }
1082
1083 RedefinitionDataIter& operator+=(ssize_t delta) {
1084 idx_ += delta;
1085 return *this;
1086 }
1087
1088 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1089 return (*holder_.GetRedefinitions())[idx_];
1090 }
1091
1092 RedefinitionDataHolder& GetHolder() {
1093 return holder_;
1094 }
1095
Vladimir Markod93e3742018-07-18 10:58:13 +01001096 art::ObjPtr<art::mirror::ClassLoader> GetSourceClassLoader() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001097 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1098 return holder_.GetSourceClassLoader(idx_);
1099 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001100 art::ObjPtr<art::mirror::Object> GetJavaDexFile() const
1101 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001102 return holder_.GetJavaDexFile(idx_);
1103 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001104 art::ObjPtr<art::mirror::LongArray> GetNewDexFileCookie() const
1105 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001106 return holder_.GetNewDexFileCookie(idx_);
1107 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001108 art::ObjPtr<art::mirror::DexCache> GetNewDexCache() const
1109 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001110 return holder_.GetNewDexCache(idx_);
1111 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001112 art::ObjPtr<art::mirror::Class> GetMirrorClass() const
1113 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001114 return holder_.GetMirrorClass(idx_);
1115 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001116 art::ObjPtr<art::mirror::Object> GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001117 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001118 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001119 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001120 art::ObjPtr<art::mirror::PointerArray> GetOldObsoleteMethods() const
Alex Light1e3926a2017-04-07 10:38:06 -07001121 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1122 return holder_.GetOldObsoleteMethods(idx_);
1123 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001124 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> GetOldDexCaches() const
Alex Light1e3926a2017-04-07 10:38:06 -07001125 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1126 return holder_.GetOldDexCaches(idx_);
1127 }
1128
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001129 int32_t GetIndex() const {
1130 return idx_;
1131 }
1132
1133 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1134 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1135 holder_.SetSourceClassLoader(idx_, loader);
1136 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001137 void SetJavaDexFile(art::ObjPtr<art::mirror::Object> dexfile)
1138 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001139 holder_.SetJavaDexFile(idx_, dexfile);
1140 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001141 void SetNewDexFileCookie(art::ObjPtr<art::mirror::LongArray> cookie)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001142 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1143 holder_.SetNewDexFileCookie(idx_, cookie);
1144 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001145 void SetNewDexCache(art::ObjPtr<art::mirror::DexCache> cache)
1146 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001147 holder_.SetNewDexCache(idx_, cache);
1148 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001149 void SetMirrorClass(art::ObjPtr<art::mirror::Class> klass)
1150 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001151 holder_.SetMirrorClass(idx_, klass);
1152 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001153 void SetOriginalDexFile(art::ObjPtr<art::mirror::Object> bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001154 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001155 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001156 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001157 void SetOldObsoleteMethods(art::ObjPtr<art::mirror::PointerArray> methods)
Alex Light1e3926a2017-04-07 10:38:06 -07001158 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1159 holder_.SetOldObsoleteMethods(idx_, methods);
1160 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001161 void SetOldDexCaches(art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)
Alex Light1e3926a2017-04-07 10:38:06 -07001162 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1163 holder_.SetOldDexCaches(idx_, caches);
1164 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001165
1166 private:
1167 int32_t idx_;
1168 RedefinitionDataHolder& holder_;
1169};
1170
1171RedefinitionDataIter RedefinitionDataHolder::begin() {
1172 return RedefinitionDataIter(0, *this);
1173}
1174
1175RedefinitionDataIter RedefinitionDataHolder::end() {
1176 return RedefinitionDataIter(Length(), *this);
1177}
1178
1179bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001180 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1181 art::StackHandleScope<2> hs(driver_->self_);
1182 std::string error;
1183 // TODO Make verification log level lower
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001184 art::verifier::FailureKind failure =
Andreas Gampea43ba3d2019-03-13 15:49:20 -07001185 art::verifier::ClassVerifier::VerifyClass(driver_->self_,
1186 dex_file_.get(),
1187 hs.NewHandle(iter.GetNewDexCache()),
1188 hs.NewHandle(GetClassLoader()),
1189 /*class_def=*/ dex_file_->GetClassDef(0),
1190 /*callbacks=*/ nullptr,
1191 /*allow_soft_failures=*/ true,
1192 /*log_level=*/
1193 art::verifier::HardFailLogMode::kLogWarning,
1194 art::Runtime::Current()->GetTargetSdkVersion(),
1195 &error);
Alex Light53330612017-10-04 15:29:53 -07001196 switch (failure) {
1197 case art::verifier::FailureKind::kNoFailure:
1198 case art::verifier::FailureKind::kSoftFailure:
1199 return true;
1200 case art::verifier::FailureKind::kHardFailure: {
1201 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1202 return false;
1203 }
Alex Light8c889d22017-02-06 13:58:27 -08001204 }
Alex Light8c889d22017-02-06 13:58:27 -08001205}
1206
Alex Light1babae02017-02-01 15:35:34 -08001207// Looks through the previously allocated cookies to see if we need to update them with another new
1208// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1209// once they are all added to the classloader.
1210bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001211 art::Handle<art::mirror::ClassLoader> source_class_loader,
1212 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001213 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001214 art::StackHandleScope<2> hs(driver_->self_);
1215 art::MutableHandle<art::mirror::LongArray> old_cookie(
1216 hs.NewHandle<art::mirror::LongArray>(nullptr));
1217 bool has_older_cookie = false;
1218 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001219 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1220 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001221 // Since every instance of this classloader should have the same cookie associated with it we
1222 // can stop looking here.
1223 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001224 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001225 break;
1226 }
1227 }
1228 if (old_cookie.IsNull()) {
1229 // No older cookie. Get it directly from the dex_file_obj
1230 // We should not have seen this classloader elsewhere.
1231 CHECK(!has_older_cookie);
1232 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1233 }
1234 // Use the old cookie to generate the new one with the new DexFile* added in.
1235 art::Handle<art::mirror::LongArray>
1236 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1237 old_cookie,
1238 dex_file_.get())));
1239 // Make sure the allocation worked.
1240 if (new_cookie.IsNull()) {
1241 return false;
1242 }
1243
1244 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001245 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001246 // If there are other copies of this same classloader we need to make sure that we all have the
1247 // same cookie.
1248 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001249 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001250 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001251 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1252 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001253 }
1254 }
1255 }
1256
1257 return true;
1258}
1259
Alex Lighta7e38d82017-01-19 14:57:28 -08001260bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001261 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001262 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001263 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001264 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001265 // This shouldn't allocate
1266 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001267 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1268 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001269 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001270 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1271 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001272 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001273 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001274 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1275 return false;
1276 }
Alex Light1babae02017-02-01 15:35:34 -08001277 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001278 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001279 driver_->self_->AssertPendingOOMException();
1280 driver_->self_->ClearException();
1281 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1282 return false;
1283 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001284 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001285 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1286 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001287 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001288 driver_->self_->ClearException();
1289 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1290 return false;
1291 }
1292
1293 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001294 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1295 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001296 driver_->self_->AssertPendingOOMException();
1297 driver_->self_->ClearException();
1298 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1299 return false;
1300 }
1301 return true;
1302}
1303
Alex Lighta26e3492017-06-27 17:55:37 -07001304void Redefiner::ClassRedefinition::UnregisterJvmtiBreakpoints() {
Vladimir Marko4617d582019-03-28 13:48:31 +00001305 BreakpointUtil::RemoveBreakpointsInClass(driver_->env_, GetMirrorClass().Ptr());
Alex Lighta26e3492017-06-27 17:55:37 -07001306}
1307
Alex Light5643caf2017-02-08 11:39:07 -08001308void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
Alex Lighte34fe442018-02-21 17:35:55 -08001309 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1310 return;
1311 }
Alex Light5643caf2017-02-08 11:39:07 -08001312 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1313 if (state != nullptr) {
1314 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1315 }
1316}
1317
1318void Redefiner::UnregisterAllBreakpoints() {
Alex Light5643caf2017-02-08 11:39:07 -08001319 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1320 redef.UnregisterBreakpoints();
Alex Lighte34fe442018-02-21 17:35:55 -08001321 redef.UnregisterJvmtiBreakpoints();
Alex Light5643caf2017-02-08 11:39:07 -08001322 }
1323}
1324
Alex Light0e692732017-01-10 15:00:05 -08001325bool Redefiner::CheckAllRedefinitionAreValid() {
1326 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1327 if (!redef.CheckRedefinitionIsValid()) {
1328 return false;
1329 }
1330 }
1331 return true;
1332}
1333
Alex Light1e3926a2017-04-07 10:38:06 -07001334void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
1335 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1336 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
1337 }
1338}
1339
1340bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
1341 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1342 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001343 return false;
1344 }
1345 }
1346 return true;
1347}
1348
1349bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001350 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001351 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001352 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001353 return false;
1354 }
Alex Light0e692732017-01-10 15:00:05 -08001355 }
1356 return true;
1357}
1358
1359void Redefiner::ClassRedefinition::ReleaseDexFile() {
Andreas Gampeafaf7f82018-10-16 11:32:38 -07001360 dex_file_.release(); // NOLINT b/117926937
Alex Light0e692732017-01-10 15:00:05 -08001361}
1362
1363void Redefiner::ReleaseAllDexFiles() {
1364 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1365 redef.ReleaseDexFile();
1366 }
1367}
1368
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001369bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1370 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1371 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001372 return false;
1373 }
Alex Light8c889d22017-02-06 13:58:27 -08001374 }
1375 return true;
1376}
1377
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001378class ScopedDisableConcurrentAndMovingGc {
1379 public:
1380 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1381 : heap_(heap), self_(self) {
1382 if (heap_->IsGcConcurrentAndMoving()) {
1383 heap_->IncrementDisableMovingGC(self_);
1384 }
1385 }
1386
1387 ~ScopedDisableConcurrentAndMovingGc() {
1388 if (heap_->IsGcConcurrentAndMoving()) {
1389 heap_->DecrementDisableMovingGC(self_);
1390 }
1391 }
1392 private:
1393 art::gc::Heap* heap_;
1394 art::Thread* self_;
1395};
1396
Alex Lighta01de592016-11-15 10:43:06 -08001397jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001398 art::StackHandleScope<1> hs(self_);
1399 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1400 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001401 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001402 if (holder.IsNull()) {
1403 self_->AssertPendingOOMException();
1404 self_->ClearException();
1405 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1406 return result_;
1407 }
1408
Alex Lighta01de592016-11-15 10:43:06 -08001409 // First we just allocate the ClassExt and its fields that we need. These can be updated
1410 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1411 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1412 // between allocating them and pausing all threads before we can update them so we need to do a
1413 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001414 if (!CheckAllRedefinitionAreValid() ||
Alex Light1e3926a2017-04-07 10:38:06 -07001415 !EnsureAllClassAllocationsFinished(holder) ||
Alex Light8c889d22017-02-06 13:58:27 -08001416 !FinishAllRemainingAllocations(holder) ||
1417 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001418 return result_;
1419 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001420
Alex Light5643caf2017-02-08 11:39:07 -08001421 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001422 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light07f06212017-06-01 14:01:43 -07001423 art::ClassLinker* cl = runtime_->GetClassLinker();
1424 cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001425 if (data.GetSourceClassLoader() == nullptr) {
Alex Light07f06212017-06-01 14:01:43 -07001426 cl->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001427 }
Alex Light7916f202017-01-27 09:00:15 -08001428 }
Alex Light5643caf2017-02-08 11:39:07 -08001429 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001430
Alex Light6abd5392017-01-05 17:53:00 -08001431 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1432 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001433 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1434
Alex Lighta01de592016-11-15 10:43:06 -08001435 // Do transition to final suspension
1436 // TODO We might want to give this its own suspended state!
1437 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001438 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
Andreas Gampe6e897762018-10-16 13:09:32 -07001439 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend=*/true);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001440 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001441 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001442 ClassRedefinition& redef = data.GetRedefinition();
1443 if (data.GetSourceClassLoader() != nullptr) {
1444 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001445 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001446 art::ObjPtr<art::mirror::Class> klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001447 // TODO Rewrite so we don't do a stack walk for each and every class.
1448 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001449 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001450 }
Alex Light1e3926a2017-04-07 10:38:06 -07001451 RestoreObsoleteMethodMapsIfUnneeded(holder);
Alex Light7532d582017-02-13 16:36:06 -08001452 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1453 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1454 // methods that have been jitted prior to the current redefinition being applied might continue
1455 // to use the old versions of the intrinsics!
Alex Light0e692732017-01-10 15:00:05 -08001456 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1457 // owns the DexFile and when ownership is transferred.
1458 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001459 return OK;
1460}
1461
Alex Light0e692732017-01-10 15:00:05 -08001462void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001463 const art::dex::ClassDef& class_def) {
Alex Light0e692732017-01-10 15:00:05 -08001464 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001465 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001466 const art::dex::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001467 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001468 // Update methods.
Alex Light00e475c2017-07-19 16:36:23 -07001469 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001470 const art::dex::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
Alex Lighta01de592016-11-15 10:43:06 -08001471 art::dex::TypeIndex method_return_idx =
1472 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1473 const auto* old_type_list = method.GetParameterTypeList();
1474 std::vector<art::dex::TypeIndex> new_type_list;
1475 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1476 new_type_list.push_back(
1477 dex_file_->GetIndexForTypeId(
1478 *dex_file_->FindTypeId(
1479 old_dex_file.GetTypeDescriptor(
1480 old_dex_file.GetTypeId(
1481 old_type_list->GetTypeItem(i).type_idx_)))));
1482 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001483 const art::dex::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx, new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001484 CHECK(proto_id != nullptr || old_type_list == nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001485 const art::dex::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1486 *new_name_id,
1487 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001488 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001489 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1490 method.SetDexMethodIndex(dex_method_idx);
1491 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001492 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Light7532d582017-02-13 16:36:06 -08001493 // Clear all the intrinsics related flags.
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +01001494 method.SetNotIntrinsic();
Alex Lighta01de592016-11-15 10:43:06 -08001495 }
Alex Light200b9d72016-12-15 11:34:13 -08001496}
1497
Alex Light0e692732017-01-10 15:00:05 -08001498void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001499 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1500 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1501 for (art::ArtField& field : fields_iter) {
1502 std::string declaring_class_name;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001503 const art::dex::TypeId* new_declaring_id =
Alex Light200b9d72016-12-15 11:34:13 -08001504 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001505 const art::dex::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1506 const art::dex::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001507 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001508 const art::dex::FieldId* new_field_id =
Alex Light200b9d72016-12-15 11:34:13 -08001509 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1510 CHECK(new_field_id != nullptr);
1511 // We only need to update the index since the other data in the ArtField cannot be updated.
1512 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1513 }
1514 }
Alex Light200b9d72016-12-15 11:34:13 -08001515}
1516
1517// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001518void Redefiner::ClassRedefinition::UpdateClass(
1519 art::ObjPtr<art::mirror::Class> mclass,
1520 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001521 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001522 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001523 const art::dex::ClassDef& class_def = dex_file_->GetClassDef(0);
Vladimir Marko5122e6b2017-08-17 16:10:09 +01001524 UpdateMethods(mclass, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001525 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001526
David Brazdil1a658632018-12-01 17:54:26 +00001527 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1528 CHECK(!ext.IsNull());
1529 ext->SetOriginalDexFile(original_dex_file);
1530
1531 // If this is the first time the class is being redefined, store
1532 // the native DexFile pointer and initial ClassDef index in ClassExt.
1533 // This preserves the pointer for hiddenapi access checks which need
1534 // to read access flags from the initial DexFile.
1535 if (ext->GetPreRedefineDexFile() == nullptr) {
1536 ext->SetPreRedefineDexFile(&mclass->GetDexFile());
1537 ext->SetPreRedefineClassDefIndex(mclass->GetDexClassDefIndex());
1538 }
1539
Alex Lighta01de592016-11-15 10:43:06 -08001540 // Update the class fields.
1541 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1542 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1543 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001544 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001545 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Light035105f2018-03-05 17:48:48 -08001546
1547 // Notify the jit that all the methods in this class were redefined. Need to do this last since
1548 // the jit relies on the dex_file_ being correct (for native methods at least) to find the method
1549 // meta-data.
1550 art::jit::Jit* jit = driver_->runtime_->GetJit();
1551 if (jit != nullptr) {
1552 art::PointerSize image_pointer_size =
1553 driver_->runtime_->GetClassLinker()->GetImagePointerSize();
1554 auto code_cache = jit->GetCodeCache();
1555 // Non-invokable methods don't have any JIT data associated with them so we don't need to tell
1556 // the jit about them.
1557 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
1558 if (method.IsInvokable()) {
1559 code_cache->NotifyMethodRedefined(&method);
1560 }
1561 }
1562 }
Alex Lighta01de592016-11-15 10:43:06 -08001563}
1564
Alex Light1e3926a2017-04-07 10:38:06 -07001565// Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
1566// obsolete methods).
1567void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
1568 const RedefinitionDataIter* cur_data) {
Vladimir Markod93e3742018-07-18 10:58:13 +01001569 art::ObjPtr<art::mirror::Class> klass = GetMirrorClass();
1570 art::ObjPtr<art::mirror::ClassExt> ext = klass->GetExtData();
1571 art::ObjPtr<art::mirror::PointerArray> methods = ext->GetObsoleteMethods();
1572 art::ObjPtr<art::mirror::PointerArray> old_methods = cur_data->GetOldObsoleteMethods();
Alex Light70713df2017-04-18 13:03:31 -07001573 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
Alex Light1e3926a2017-04-07 10:38:06 -07001574 int32_t expected_length =
1575 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
1576 // Check to make sure we are only undoing this one.
1577 if (expected_length == methods->GetLength()) {
Alex Light70713df2017-04-18 13:03:31 -07001578 for (int32_t i = 0; i < expected_length; i++) {
1579 art::ArtMethod* expected = nullptr;
1580 if (i < old_length) {
1581 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
1582 }
1583 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
Alex Light1e3926a2017-04-07 10:38:06 -07001584 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
1585 // obsolete methods array.
1586 return;
1587 }
1588 }
1589 // No new obsolete methods! We can get rid of the maps.
1590 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
1591 }
1592}
1593
Alex Lighta01de592016-11-15 10:43:06 -08001594// This function does all (java) allocations we need to do for the Class being redefined.
1595// TODO Change this name maybe?
Alex Light1e3926a2017-04-07 10:38:06 -07001596bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
1597 /*out*/RedefinitionDataIter* cur_data) {
Alex Light0e692732017-01-10 15:00:05 -08001598 art::StackHandleScope<2> hs(driver_->self_);
1599 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1600 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001601 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001602 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1603 return false;
1604 }
1605 // Allocate the classExt
Vladimir Marko3068d582019-05-28 16:39:29 +01001606 art::Handle<art::mirror::ClassExt> ext =
1607 hs.NewHandle(art::mirror::Class::EnsureExtDataPresent(klass, driver_->self_));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001608 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001609 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001610 driver_->self_->AssertPendingOOMException();
1611 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001612 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1613 return false;
1614 }
Alex Light1e3926a2017-04-07 10:38:06 -07001615 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
1616 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
Alex Lighta01de592016-11-15 10:43:06 -08001617 // are only modified when all threads (other than the modifying one) are suspended we don't need
1618 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1619 // however, since that can happen at any time.
Alex Light1e3926a2017-04-07 10:38:06 -07001620 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
1621 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
Vladimir Marko3068d582019-05-28 16:39:29 +01001622 if (!art::mirror::ClassExt::ExtendObsoleteArrays(
1623 ext, driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
Alex Light1e3926a2017-04-07 10:38:06 -07001624 // OOM. Clear exception and return error.
1625 driver_->self_->AssertPendingOOMException();
1626 driver_->self_->ClearException();
1627 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1628 return false;
Alex Lighta01de592016-11-15 10:43:06 -08001629 }
1630 return true;
1631}
1632
1633} // namespace openjdkjvmti