blob: 975843c823fae3552cc2b2eb77d15a4c7f4bdad1 [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 Light038063c2019-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 Light038063c2019-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 Light038063c2019-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 Light038063c2019-04-10 14:22:49 -0700141 struct ObsoleteMethodPair {
142 art::ArtMethod* old_method;
143 art::ArtMethod* obsolete_method;
144 };
145
146 class ObsoleteMapIter : public std::iterator<std::forward_iterator_tag, ObsoleteMethodPair> {
147 public:
148 ObsoleteMethodPair operator*() const
149 REQUIRES(art::Locks::mutator_lock_, art::Roles::uninterruptible_) {
150 art::ArtMethod* obsolete = map_->FindObsoleteVersion(iter_->first);
151 DCHECK(obsolete != nullptr);
152 return { iter_->first, obsolete };
153 }
154
155 bool operator==(ObsoleteMapIter other) const {
156 return map_ == other.map_ && iter_ == other.iter_;
157 }
158
159 bool operator!=(ObsoleteMapIter other) const {
160 return !(*this == other);
161 }
162
163 ObsoleteMapIter operator++(int) const {
164 ObsoleteMapIter retval = *this;
165 ++(*this);
166 return retval;
167 }
168
169 ObsoleteMapIter operator++() const {
170 ++iter_;
171 return *this;
172 }
173
174 private:
175 ObsoleteMapIter(const ObsoleteMap* map,
176 std::unordered_map<art::ArtMethod*, int32_t>::const_iterator iter)
177 : map_(map), iter_(iter) {}
178
179 const ObsoleteMap* map_;
180 mutable std::unordered_map<art::ArtMethod*, int32_t>::const_iterator iter_;
181
182 friend class ObsoleteMap;
183 };
184
185 ObsoleteMapIter end() const {
186 return ObsoleteMapIter(this, id_map_.cend());
187 }
188
189 ObsoleteMapIter begin() const {
190 return ObsoleteMapIter(this, id_map_.cbegin());
191 }
192
Alex Lighteee0bd42017-02-14 15:31:45 +0000193 private:
194 int32_t next_free_slot_;
195 std::unordered_map<art::ArtMethod*, int32_t> id_map_;
196 // Pointers to the fields in mirror::ClassExt. These can be held as ObjPtr since this is only used
197 // when we have an exclusive mutator_lock_ (i.e. all threads are suspended).
198 art::ObjPtr<art::mirror::PointerArray> obsolete_methods_;
199 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> obsolete_dex_caches_;
200 art::ObjPtr<art::mirror::DexCache> original_dex_cache_;
201};
202
Alex Lightdba61482016-12-21 08:20:29 -0800203// This visitor walks thread stacks and allocates and sets up the obsolete methods. It also does
204// some basic sanity checks that the obsolete method is sane.
205class ObsoleteMethodStackVisitor : public art::StackVisitor {
206 protected:
207 ObsoleteMethodStackVisitor(
208 art::Thread* thread,
209 art::LinearAlloc* allocator,
210 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000211 ObsoleteMap* obsolete_maps)
Alex Lightdba61482016-12-21 08:20:29 -0800212 : StackVisitor(thread,
Andreas Gampe6e897762018-10-16 13:09:32 -0700213 /*context=*/nullptr,
Alex Lightdba61482016-12-21 08:20:29 -0800214 StackVisitor::StackWalkKind::kIncludeInlinedFrames),
215 allocator_(allocator),
216 obsoleted_methods_(obsoleted_methods),
Alex Light4ba388a2017-01-27 10:26:49 -0800217 obsolete_maps_(obsolete_maps) { }
Alex Lightdba61482016-12-21 08:20:29 -0800218
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100219 ~ObsoleteMethodStackVisitor() override {}
Alex Lightdba61482016-12-21 08:20:29 -0800220
221 public:
222 // Returns true if we successfully installed obsolete methods on this thread, filling
223 // obsolete_maps_ with the translations if needed. Returns false and fills error_msg if we fail.
224 // The stack is cleaned up when we fail.
Alex Light007ada22017-01-10 13:33:56 -0800225 static void UpdateObsoleteFrames(
Alex Lightdba61482016-12-21 08:20:29 -0800226 art::Thread* thread,
227 art::LinearAlloc* allocator,
228 const std::unordered_set<art::ArtMethod*>& obsoleted_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000229 ObsoleteMap* obsolete_maps)
Alex Light007ada22017-01-10 13:33:56 -0800230 REQUIRES(art::Locks::mutator_lock_) {
Alex Lightdba61482016-12-21 08:20:29 -0800231 ObsoleteMethodStackVisitor visitor(thread,
232 allocator,
233 obsoleted_methods,
Alex Light007ada22017-01-10 13:33:56 -0800234 obsolete_maps);
Alex Lightdba61482016-12-21 08:20:29 -0800235 visitor.WalkStack();
Alex Lightdba61482016-12-21 08:20:29 -0800236 }
237
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100238 bool VisitFrame() override REQUIRES(art::Locks::mutator_lock_) {
Alex Lighteee0bd42017-02-14 15:31:45 +0000239 art::ScopedAssertNoThreadSuspension snts("Fixing up the stack for obsolete methods.");
Alex Lightdba61482016-12-21 08:20:29 -0800240 art::ArtMethod* old_method = GetMethod();
Alex Lightdba61482016-12-21 08:20:29 -0800241 if (obsoleted_methods_.find(old_method) != obsoleted_methods_.end()) {
Alex Lightdba61482016-12-21 08:20:29 -0800242 // We cannot ensure that the right dex file is used in inlined frames so we don't support
243 // redefining them.
Nicolas Geoffray226805d2018-12-14 10:59:02 +0000244 DCHECK(!IsInInlinedFrame()) << "Inlined frames are not supported when using redefinition: "
245 << old_method->PrettyMethod() << " is inlined into "
246 << GetOuterMethod()->PrettyMethod();
Alex Lighteee0bd42017-02-14 15:31:45 +0000247 art::ArtMethod* new_obsolete_method = obsolete_maps_->FindObsoleteVersion(old_method);
248 if (new_obsolete_method == nullptr) {
Alex Lightdba61482016-12-21 08:20:29 -0800249 // Create a new Obsolete Method and put it in the list.
250 art::Runtime* runtime = art::Runtime::Current();
251 art::ClassLinker* cl = runtime->GetClassLinker();
252 auto ptr_size = cl->GetImagePointerSize();
253 const size_t method_size = art::ArtMethod::Size(ptr_size);
Alex Light5c11a792017-03-10 14:29:22 -0800254 auto* method_storage = allocator_->Alloc(art::Thread::Current(), method_size);
Alex Light007ada22017-01-10 13:33:56 -0800255 CHECK(method_storage != nullptr) << "Unable to allocate storage for obsolete version of '"
256 << old_method->PrettyMethod() << "'";
Alex Lightdba61482016-12-21 08:20:29 -0800257 new_obsolete_method = new (method_storage) art::ArtMethod();
258 new_obsolete_method->CopyFrom(old_method, ptr_size);
259 DCHECK_EQ(new_obsolete_method->GetDeclaringClass(), old_method->GetDeclaringClass());
260 new_obsolete_method->SetIsObsolete();
Alex Lightfcbafb32017-02-02 15:09:54 -0800261 new_obsolete_method->SetDontCompile();
Alex Lightdb01a092017-04-03 15:39:55 -0700262 cl->SetEntryPointsForObsoleteMethod(new_obsolete_method);
Alex Lighteee0bd42017-02-14 15:31:45 +0000263 obsolete_maps_->RecordObsolete(old_method, new_obsolete_method);
Alex Lightdba61482016-12-21 08:20:29 -0800264 }
265 DCHECK(new_obsolete_method != nullptr);
266 SetMethod(new_obsolete_method);
267 }
268 return true;
269 }
270
271 private:
272 // The linear allocator we should use to make new methods.
273 art::LinearAlloc* allocator_;
274 // The set of all methods which could be obsoleted.
275 const std::unordered_set<art::ArtMethod*>& obsoleted_methods_;
276 // A map from the original to the newly allocated obsolete method for frames on this thread. The
Alex Lighteee0bd42017-02-14 15:31:45 +0000277 // values in this map are added to the obsolete_methods_ (and obsolete_dex_caches_) fields of
278 // the redefined classes ClassExt as it is filled.
279 ObsoleteMap* obsolete_maps_;
Alex Lightdba61482016-12-21 08:20:29 -0800280};
281
Alex Lighte4a88632017-01-10 07:41:24 -0800282jvmtiError Redefiner::IsModifiableClass(jvmtiEnv* env ATTRIBUTE_UNUSED,
283 jclass klass,
284 jboolean* is_redefinable) {
Alex Lighte4a88632017-01-10 07:41:24 -0800285 art::Thread* self = art::Thread::Current();
286 art::ScopedObjectAccess soa(self);
287 art::StackHandleScope<1> hs(self);
288 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
Alex Light413a8ad2019-02-14 10:19:44 -0800289 if (obj.IsNull() || !obj->IsClass()) {
Alex Lighte4a88632017-01-10 07:41:24 -0800290 return ERR(INVALID_CLASS);
291 }
292 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
293 std::string err_unused;
294 *is_redefinable =
Alex Light9e7859c2018-04-05 13:49:43 -0700295 Redefiner::GetClassRedefinitionError(h_klass, &err_unused) != ERR(UNMODIFIABLE_CLASS)
296 ? JNI_TRUE : JNI_FALSE;
Alex Lighte4a88632017-01-10 07:41:24 -0800297 return OK;
298}
299
Alex Light9e7859c2018-04-05 13:49:43 -0700300jvmtiError Redefiner::GetClassRedefinitionError(jclass klass, /*out*/std::string* error_msg) {
301 art::Thread* self = art::Thread::Current();
302 art::ScopedObjectAccess soa(self);
303 art::StackHandleScope<1> hs(self);
304 art::ObjPtr<art::mirror::Object> obj(self->DecodeJObject(klass));
Alex Light413a8ad2019-02-14 10:19:44 -0800305 if (obj.IsNull() || !obj->IsClass()) {
Alex Light9e7859c2018-04-05 13:49:43 -0700306 return ERR(INVALID_CLASS);
307 }
308 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(obj->AsClass()));
309 return Redefiner::GetClassRedefinitionError(h_klass, error_msg);
310}
311
Alex Lighte4a88632017-01-10 07:41:24 -0800312jvmtiError Redefiner::GetClassRedefinitionError(art::Handle<art::mirror::Class> klass,
313 /*out*/std::string* error_msg) {
Alex Light9e7859c2018-04-05 13:49:43 -0700314 if (!klass->IsResolved()) {
315 // It's only a problem to try to retransform/redefine a unprepared class if it's happening on
316 // the same thread as the class-linking process. If it's on another thread we will be able to
317 // wait for the preparation to finish and continue from there.
318 if (klass->GetLockOwnerThreadId() == art::Thread::Current()->GetThreadId()) {
319 *error_msg = "Modification of class " + klass->PrettyClass() +
320 " from within the classes ClassLoad callback is not supported to prevent deadlocks." +
321 " Please use ClassFileLoadHook directly instead.";
322 return ERR(INTERNAL);
323 } else {
324 LOG(WARNING) << klass->PrettyClass() << " is not yet resolved. Attempting to transform "
325 << "it could cause arbitrary length waits as the class is being resolved.";
326 }
327 }
Alex Lighte4a88632017-01-10 07:41:24 -0800328 if (klass->IsPrimitive()) {
329 *error_msg = "Modification of primitive classes is not supported";
330 return ERR(UNMODIFIABLE_CLASS);
331 } else if (klass->IsInterface()) {
332 *error_msg = "Modification of Interface classes is currently not supported";
333 return ERR(UNMODIFIABLE_CLASS);
Alex Light09f274f2017-02-21 15:00:48 -0800334 } else if (klass->IsStringClass()) {
335 *error_msg = "Modification of String class is not supported";
336 return ERR(UNMODIFIABLE_CLASS);
Alex Lighte4a88632017-01-10 07:41:24 -0800337 } else if (klass->IsArrayClass()) {
338 *error_msg = "Modification of Array classes is not supported";
339 return ERR(UNMODIFIABLE_CLASS);
340 } else if (klass->IsProxyClass()) {
341 *error_msg = "Modification of proxy classes is not supported";
342 return ERR(UNMODIFIABLE_CLASS);
343 }
344
Alex Lighte77b48b2017-02-22 11:08:06 -0800345 for (jclass c : art::NonDebuggableClasses::GetNonDebuggableClasses()) {
346 if (klass.Get() == art::Thread::Current()->DecodeJObject(c)->AsClass()) {
347 *error_msg = "Class might have stack frames that cannot be made obsolete";
348 return ERR(UNMODIFIABLE_CLASS);
349 }
350 }
351
Alex Lighte4a88632017-01-10 07:41:24 -0800352 return OK;
353}
354
Alex Lighta01de592016-11-15 10:43:06 -0800355// Moves dex data to an anonymous, read-only mmap'd region.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100356art::MemMap Redefiner::MoveDataToMemMap(const std::string& original_location,
357 art::ArrayRef<const unsigned char> data,
358 std::string* error_msg) {
359 art::MemMap map = art::MemMap::MapAnonymous(
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800360 StringPrintf("%s-transformed", original_location.c_str()).c_str(),
Alex Lightb7354d52017-03-30 15:17:01 -0700361 data.size(),
Alex Lighta01de592016-11-15 10:43:06 -0800362 PROT_READ|PROT_WRITE,
Andreas Gampe6e897762018-10-16 13:09:32 -0700363 /*low_4gb=*/ false,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100364 error_msg);
365 if (LIKELY(map.IsValid())) {
366 memcpy(map.Begin(), data.data(), data.size());
367 // Make the dex files mmap read only. This matches how other DexFiles are mmaped and prevents
368 // programs from corrupting it.
369 map.Protect(PROT_READ);
Alex Lighta01de592016-11-15 10:43:06 -0800370 }
Alex Lighta01de592016-11-15 10:43:06 -0800371 return map;
372}
373
Alex Lighta7e38d82017-01-19 14:57:28 -0800374Redefiner::ClassRedefinition::ClassRedefinition(
375 Redefiner* driver,
376 jclass klass,
377 const art::DexFile* redefined_dex_file,
378 const char* class_sig,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100379 art::ArrayRef<const unsigned char> orig_dex_file) :
Alex Lighta7e38d82017-01-19 14:57:28 -0800380 driver_(driver),
381 klass_(klass),
382 dex_file_(redefined_dex_file),
383 class_sig_(class_sig),
384 original_dex_file_(orig_dex_file) {
Alex Light0e692732017-01-10 15:00:05 -0800385 GetMirrorClass()->MonitorEnter(driver_->self_);
386}
387
388Redefiner::ClassRedefinition::~ClassRedefinition() {
389 if (driver_ != nullptr) {
390 GetMirrorClass()->MonitorExit(driver_->self_);
391 }
392}
393
Alex Light0e692732017-01-10 15:00:05 -0800394jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env,
Andreas Gampede19eb92017-02-24 16:21:18 -0800395 EventHandler* event_handler,
Alex Light0e692732017-01-10 15:00:05 -0800396 art::Runtime* runtime,
397 art::Thread* self,
398 jint class_count,
399 const jvmtiClassDefinition* definitions,
Alex Light6ac57502017-01-19 15:05:06 -0800400 /*out*/std::string* error_msg) {
Alex Light0e692732017-01-10 15:00:05 -0800401 if (env == nullptr) {
402 *error_msg = "env was null!";
403 return ERR(INVALID_ENVIRONMENT);
404 } else if (class_count < 0) {
405 *error_msg = "class_count was less then 0";
406 return ERR(ILLEGAL_ARGUMENT);
407 } else if (class_count == 0) {
408 // We don't actually need to do anything. Just return OK.
409 return OK;
410 } else if (definitions == nullptr) {
411 *error_msg = "null definitions!";
412 return ERR(NULL_POINTER);
413 }
Alex Light6ac57502017-01-19 15:05:06 -0800414 std::vector<ArtClassDefinition> def_vector;
415 def_vector.reserve(class_count);
416 for (jint i = 0; i < class_count; i++) {
Alex Light9e7859c2018-04-05 13:49:43 -0700417 jvmtiError res = Redefiner::GetClassRedefinitionError(definitions[i].klass, error_msg);
Alex Lightce6ee702017-03-06 15:46:43 -0800418 if (res != OK) {
419 return res;
Alex Lightce6ee702017-03-06 15:46:43 -0800420 }
Alex Light6ac57502017-01-19 15:05:06 -0800421 ArtClassDefinition def;
Alex Light64e4c142018-01-30 13:46:37 -0800422 res = def.Init(self, definitions[i]);
Alex Light6ac57502017-01-19 15:05:06 -0800423 if (res != OK) {
424 return res;
425 }
426 def_vector.push_back(std::move(def));
427 }
428 // Call all the transformation events.
Alex Light64e4c142018-01-30 13:46:37 -0800429 jvmtiError res = Transformer::RetransformClassesDirect(event_handler,
Alex Light6ac57502017-01-19 15:05:06 -0800430 self,
431 &def_vector);
432 if (res != OK) {
433 // Something went wrong with transformation!
434 return res;
435 }
436 return RedefineClassesDirect(env, runtime, self, def_vector, error_msg);
437}
438
439jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env,
440 art::Runtime* runtime,
441 art::Thread* self,
442 const std::vector<ArtClassDefinition>& definitions,
443 std::string* error_msg) {
444 DCHECK(env != nullptr);
445 if (definitions.size() == 0) {
446 // We don't actually need to do anything. Just return OK.
447 return OK;
448 }
Alex Light0e692732017-01-10 15:00:05 -0800449 // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we
450 // are going to redefine.
451 art::jit::ScopedJitSuspend suspend_jit;
452 // Get shared mutator lock so we can lock all the classes.
453 art::ScopedObjectAccess soa(self);
Alex Lighta26e3492017-06-27 17:55:37 -0700454 Redefiner r(env, runtime, self, error_msg);
Alex Light6ac57502017-01-19 15:05:06 -0800455 for (const ArtClassDefinition& def : definitions) {
456 // Only try to transform classes that have been modified.
Alex Light40528472017-03-28 09:07:36 -0700457 if (def.IsModified()) {
Alex Light6ac57502017-01-19 15:05:06 -0800458 jvmtiError res = r.AddRedefinition(env, def);
459 if (res != OK) {
460 return res;
461 }
Alex Light0e692732017-01-10 15:00:05 -0800462 }
463 }
464 return r.Run();
465}
466
Alex Light6ac57502017-01-19 15:05:06 -0800467jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) {
Alex Light0e692732017-01-10 15:00:05 -0800468 std::string original_dex_location;
469 jvmtiError ret = OK;
Alex Lightb7354d52017-03-30 15:17:01 -0700470 if ((ret = GetClassLocation(env, def.GetClass(), &original_dex_location))) {
Alex Light0e692732017-01-10 15:00:05 -0800471 *error_msg_ = "Unable to get original dex file location!";
472 return ret;
473 }
Alex Light52a2db52017-01-19 23:00:21 +0000474 char* generic_ptr_unused = nullptr;
475 char* signature_ptr = nullptr;
Alex Lightb7354d52017-03-30 15:17:01 -0700476 if ((ret = env->GetClassSignature(def.GetClass(), &signature_ptr, &generic_ptr_unused)) != OK) {
Alex Light6ac57502017-01-19 15:05:06 -0800477 *error_msg_ = "Unable to get class signature!";
478 return ret;
Alex Light52a2db52017-01-19 23:00:21 +0000479 }
Andreas Gampe54711412017-02-21 12:41:43 -0800480 JvmtiUniquePtr<char> generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused));
481 JvmtiUniquePtr<char> signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr));
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100482 art::MemMap map = MoveDataToMemMap(original_dex_location, def.GetDexData(), error_msg_);
Alex Light6ac57502017-01-19 15:05:06 -0800483 std::ostringstream os;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100484 if (!map.IsValid()) {
Alex Lightb7354d52017-03-30 15:17:01 -0700485 os << "Failed to create anonymous mmap for modified dex file of class " << def.GetName()
Alex Light0e692732017-01-10 15:00:05 -0800486 << "in dex file " << original_dex_location << " because: " << *error_msg_;
487 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800488 return ERR(OUT_OF_MEMORY);
489 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100490 if (map.Size() < sizeof(art::DexFile::Header)) {
Alex Light0e692732017-01-10 15:00:05 -0800491 *error_msg_ = "Could not read dex file header because dex_data was too short";
Alex Lighta01de592016-11-15 10:43:06 -0800492 return ERR(INVALID_CLASS_FORMAT);
493 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100494 std::string name = map.GetName();
495 uint32_t checksum = reinterpret_cast<const art::DexFile::Header*>(map.Begin())->checksum_;
David Sehr013fd802018-01-11 22:55:24 -0800496 const art::ArtDexFileLoader dex_file_loader;
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100497 std::unique_ptr<const art::DexFile> dex_file(dex_file_loader.Open(name,
David Sehr013fd802018-01-11 22:55:24 -0800498 checksum,
499 std::move(map),
Andreas Gampe6e897762018-10-16 13:09:32 -0700500 /*verify=*/true,
501 /*verify_checksum=*/true,
David Sehr013fd802018-01-11 22:55:24 -0800502 error_msg_));
Alex Lighta01de592016-11-15 10:43:06 -0800503 if (dex_file.get() == nullptr) {
Alex Lightb7354d52017-03-30 15:17:01 -0700504 os << "Unable to load modified dex file for " << def.GetName() << ": " << *error_msg_;
Alex Light0e692732017-01-10 15:00:05 -0800505 *error_msg_ = os.str();
Alex Lighta01de592016-11-15 10:43:06 -0800506 return ERR(INVALID_CLASS_FORMAT);
507 }
Alex Light0e692732017-01-10 15:00:05 -0800508 redefinitions_.push_back(
Alex Lighta7e38d82017-01-19 14:57:28 -0800509 Redefiner::ClassRedefinition(this,
Alex Lightb7354d52017-03-30 15:17:01 -0700510 def.GetClass(),
Alex Lighta7e38d82017-01-19 14:57:28 -0800511 dex_file.release(),
512 signature_ptr,
Alex Light40528472017-03-28 09:07:36 -0700513 def.GetNewOriginalDexFile()));
Alex Light0e692732017-01-10 15:00:05 -0800514 return OK;
Alex Lighta01de592016-11-15 10:43:06 -0800515}
516
Vladimir Marko4617d582019-03-28 13:48:31 +0000517art::ObjPtr<art::mirror::Class> Redefiner::ClassRedefinition::GetMirrorClass() {
Alex Light0e692732017-01-10 15:00:05 -0800518 return driver_->self_->DecodeJObject(klass_)->AsClass();
Alex Lighta01de592016-11-15 10:43:06 -0800519}
520
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000521art::ObjPtr<art::mirror::ClassLoader> Redefiner::ClassRedefinition::GetClassLoader() {
Alex Lighta01de592016-11-15 10:43:06 -0800522 return GetMirrorClass()->GetClassLoader();
523}
524
Alex Light0e692732017-01-10 15:00:05 -0800525art::mirror::DexCache* Redefiner::ClassRedefinition::CreateNewDexCache(
526 art::Handle<art::mirror::ClassLoader> loader) {
Alex Light07f06212017-06-01 14:01:43 -0700527 art::StackHandleScope<2> hs(driver_->self_);
528 art::ClassLinker* cl = driver_->runtime_->GetClassLinker();
529 art::Handle<art::mirror::DexCache> cache(hs.NewHandle(
530 art::ObjPtr<art::mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100531 art::GetClassRoot<art::mirror::DexCache>(cl)->AllocObject(driver_->self_))));
Alex Light07f06212017-06-01 14:01:43 -0700532 if (cache.IsNull()) {
533 driver_->self_->AssertPendingOOMException();
534 return nullptr;
535 }
536 art::Handle<art::mirror::String> location(hs.NewHandle(
537 cl->GetInternTable()->InternStrong(dex_file_->GetLocation().c_str())));
538 if (location.IsNull()) {
539 driver_->self_->AssertPendingOOMException();
540 return nullptr;
541 }
542 art::WriterMutexLock mu(driver_->self_, *art::Locks::dex_lock_);
543 art::mirror::DexCache::InitializeDexCache(driver_->self_,
544 cache.Get(),
545 location.Get(),
546 dex_file_.get(),
547 loader.IsNull() ? driver_->runtime_->GetLinearAlloc()
548 : loader->GetAllocator(),
549 art::kRuntimePointerSize);
550 return cache.Get();
Alex Lighta01de592016-11-15 10:43:06 -0800551}
552
Alex Light0e692732017-01-10 15:00:05 -0800553void Redefiner::RecordFailure(jvmtiError result,
554 const std::string& class_sig,
555 const std::string& error_msg) {
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800556 *error_msg_ = StringPrintf("Unable to perform redefinition of '%s': %s",
Alex Light0e692732017-01-10 15:00:05 -0800557 class_sig.c_str(),
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800558 error_msg.c_str());
Alex Lighta01de592016-11-15 10:43:06 -0800559 result_ = result;
560}
561
Alex Light2f814aa2017-03-24 15:21:34 +0000562art::mirror::Object* Redefiner::ClassRedefinition::AllocateOrGetOriginalDexFile() {
Alex Lighta7e38d82017-01-19 14:57:28 -0800563 // If we have been specifically given a new set of bytes use that
564 if (original_dex_file_.size() != 0) {
Alex Light440b5d92017-01-24 15:32:25 -0800565 return art::mirror::ByteArray::AllocateAndFill(
566 driver_->self_,
Vladimir Markoe1993c72017-06-14 17:01:38 +0100567 reinterpret_cast<const signed char*>(original_dex_file_.data()),
Vladimir Markobcf17522018-06-01 13:14:32 +0100568 original_dex_file_.size()).Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800569 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800570
571 // See if we already have one set.
572 art::ObjPtr<art::mirror::ClassExt> ext(GetMirrorClass()->GetExtData());
573 if (!ext.IsNull()) {
Alex Light2f814aa2017-03-24 15:21:34 +0000574 art::ObjPtr<art::mirror::Object> old_original_dex_file(ext->GetOriginalDexFile());
575 if (!old_original_dex_file.IsNull()) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800576 // We do. Use it.
Alex Light2f814aa2017-03-24 15:21:34 +0000577 return old_original_dex_file.Ptr();
Alex Lighta7e38d82017-01-19 14:57:28 -0800578 }
Alex Lighta01de592016-11-15 10:43:06 -0800579 }
Alex Lighta7e38d82017-01-19 14:57:28 -0800580
Alex Light2f814aa2017-03-24 15:21:34 +0000581 // return the current dex_cache which has the dex file in it.
582 art::ObjPtr<art::mirror::DexCache> current_dex_cache(GetMirrorClass()->GetDexCache());
Alex Lighta7e38d82017-01-19 14:57:28 -0800583 // TODO Handle this or make it so it cannot happen.
Alex Light2f814aa2017-03-24 15:21:34 +0000584 if (current_dex_cache->GetDexFile()->NumClassDefs() != 1) {
Alex Lighta7e38d82017-01-19 14:57:28 -0800585 LOG(WARNING) << "Current dex file has more than one class in it. Calling RetransformClasses "
586 << "on this class might fail if no transformations are applied to it!";
Alex Lighta01de592016-11-15 10:43:06 -0800587 }
Alex Light2f814aa2017-03-24 15:21:34 +0000588 return current_dex_cache.Ptr();
Alex Lighta01de592016-11-15 10:43:06 -0800589}
590
Alex Lightdba61482016-12-21 08:20:29 -0800591struct CallbackCtx {
Alex Lighteee0bd42017-02-14 15:31:45 +0000592 ObsoleteMap* obsolete_map;
Alex Lightdba61482016-12-21 08:20:29 -0800593 art::LinearAlloc* allocator;
Alex Lightdba61482016-12-21 08:20:29 -0800594 std::unordered_set<art::ArtMethod*> obsolete_methods;
Alex Lightdba61482016-12-21 08:20:29 -0800595
Alex Lighteee0bd42017-02-14 15:31:45 +0000596 explicit CallbackCtx(ObsoleteMap* map, art::LinearAlloc* alloc)
597 : obsolete_map(map), allocator(alloc) {}
Alex Lightdba61482016-12-21 08:20:29 -0800598};
599
Alex Lightdba61482016-12-21 08:20:29 -0800600void DoAllocateObsoleteMethodsCallback(art::Thread* t, void* vdata) NO_THREAD_SAFETY_ANALYSIS {
601 CallbackCtx* data = reinterpret_cast<CallbackCtx*>(vdata);
Alex Light007ada22017-01-10 13:33:56 -0800602 ObsoleteMethodStackVisitor::UpdateObsoleteFrames(t,
603 data->allocator,
604 data->obsolete_methods,
Alex Lighteee0bd42017-02-14 15:31:45 +0000605 data->obsolete_map);
Alex Lightdba61482016-12-21 08:20:29 -0800606}
607
608// This creates any ArtMethod* structures needed for obsolete methods and ensures that the stack is
609// updated so they will be run.
Alex Light0e692732017-01-10 15:00:05 -0800610// TODO Rewrite so we can do this only once regardless of how many redefinitions there are.
Vladimir Markod93e3742018-07-18 10:58:13 +0100611void Redefiner::ClassRedefinition::FindAndAllocateObsoleteMethods(
612 art::ObjPtr<art::mirror::Class> art_klass) {
Alex Lightdba61482016-12-21 08:20:29 -0800613 art::ScopedAssertNoThreadSuspension ns("No thread suspension during thread stack walking");
Vladimir Markod93e3742018-07-18 10:58:13 +0100614 art::ObjPtr<art::mirror::ClassExt> ext = art_klass->GetExtData();
Alex Lightdba61482016-12-21 08:20:29 -0800615 CHECK(ext->GetObsoleteMethods() != nullptr);
Alex Light7916f202017-01-27 09:00:15 -0800616 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighteee0bd42017-02-14 15:31:45 +0000617 // This holds pointers to the obsolete methods map fields which are updated as needed.
618 ObsoleteMap map(ext->GetObsoleteMethods(), ext->GetObsoleteDexCaches(), art_klass->GetDexCache());
619 CallbackCtx ctx(&map, linker->GetAllocatorForClassLoader(art_klass->GetClassLoader()));
Alex Lightdba61482016-12-21 08:20:29 -0800620 // Add all the declared methods to the map
621 for (auto& m : art_klass->GetDeclaredMethods(art::kRuntimePointerSize)) {
Alex Light7532d582017-02-13 16:36:06 -0800622 if (m.IsIntrinsic()) {
623 LOG(WARNING) << "Redefining intrinsic method " << m.PrettyMethod() << ". This may cause the "
624 << "unexpected use of the original definition of " << m.PrettyMethod() << "in "
625 << "methods that have already been compiled.";
626 }
Alex Lighteee0bd42017-02-14 15:31:45 +0000627 // It is possible to simply filter out some methods where they cannot really become obsolete,
628 // such as native methods and keep their original (possibly optimized) implementations. We don't
629 // do this, however, since we would need to mark these functions (still in the classes
630 // declared_methods array) as obsolete so we will find the correct dex file to get meta-data
631 // from (for example about stack-frame size). Furthermore we would be unable to get some useful
632 // error checking from the interpreter which ensure we don't try to start executing obsolete
633 // methods.
Nicolas Geoffray7558d272017-02-10 10:01:47 +0000634 ctx.obsolete_methods.insert(&m);
Alex Lightdba61482016-12-21 08:20:29 -0800635 }
636 {
Alex Light0e692732017-01-10 15:00:05 -0800637 art::MutexLock mu(driver_->self_, *art::Locks::thread_list_lock_);
Alex Lightdba61482016-12-21 08:20:29 -0800638 art::ThreadList* list = art::Runtime::Current()->GetThreadList();
639 list->ForEach(DoAllocateObsoleteMethodsCallback, static_cast<void*>(&ctx));
Alex Light038063c2019-04-10 14:22:49 -0700640 // Update JIT Data structures to point to the new method.
641 art::jit::Jit* jit = art::Runtime::Current()->GetJit();
642 if (jit != nullptr) {
643 for (const ObsoleteMap::ObsoleteMethodPair& it : *ctx.obsolete_map) {
644 // Notify the JIT we are making this obsolete method. It will update the jit's internal
645 // structures to keep track of the new obsolete method.
646 jit->GetCodeCache()->MoveObsoleteMethod(it.old_method, it.obsolete_method);
647 }
648 }
Alex Lightdba61482016-12-21 08:20:29 -0800649 }
Alex Lightdba61482016-12-21 08:20:29 -0800650}
651
Alex Light6161f132017-01-25 10:30:20 -0800652// Try and get the declared method. First try to get a virtual method then a direct method if that's
653// not found.
654static art::ArtMethod* FindMethod(art::Handle<art::mirror::Class> klass,
Vladimir Markoeb37ba52019-02-05 14:10:38 +0000655 std::string_view name,
Alex Light6161f132017-01-25 10:30:20 -0800656 art::Signature sig) REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markoba118822017-06-12 15:41:56 +0100657 DCHECK(!klass->IsProxyClass());
658 for (art::ArtMethod& m : klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize)) {
659 if (m.GetName() == name && m.GetSignature() == sig) {
660 return &m;
661 }
Alex Light6161f132017-01-25 10:30:20 -0800662 }
Vladimir Markoba118822017-06-12 15:41:56 +0100663 return nullptr;
Alex Light6161f132017-01-25 10:30:20 -0800664}
665
666bool Redefiner::ClassRedefinition::CheckSameMethods() {
667 art::StackHandleScope<1> hs(driver_->self_);
668 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
669 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
670
Alex Light6161f132017-01-25 10:30:20 -0800671 // Make sure we have the same number of methods.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700672 art::ClassAccessor accessor(*dex_file_, dex_file_->GetClassDef(0));
673 uint32_t num_new_method = accessor.NumMethods();
Alex Light6161f132017-01-25 10:30:20 -0800674 uint32_t num_old_method = h_klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size();
675 if (num_new_method != num_old_method) {
676 bool bigger = num_new_method > num_old_method;
677 RecordFailure(bigger ? ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED)
678 : ERR(UNSUPPORTED_REDEFINITION_METHOD_DELETED),
679 StringPrintf("Total number of declared methods changed from %d to %d",
680 num_old_method, num_new_method));
681 return false;
682 }
683
684 // Skip all of the fields. We should have already checked this.
Alex Light6161f132017-01-25 10:30:20 -0800685 // Check each of the methods. NB we don't need to specifically check for removals since the 2 dex
686 // files have the same number of methods, which means there must be an equal amount of additions
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700687 // and removals. We should have already checked the fields.
688 for (const art::ClassAccessor::Method& method : accessor.GetMethods()) {
Alex Light6161f132017-01-25 10:30:20 -0800689 // Get the data on the method we are searching for
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800690 const art::dex::MethodId& new_method_id = dex_file_->GetMethodId(method.GetIndex());
Alex Light6161f132017-01-25 10:30:20 -0800691 const char* new_method_name = dex_file_->GetMethodName(new_method_id);
692 art::Signature new_method_signature = dex_file_->GetMethodSignature(new_method_id);
693 art::ArtMethod* old_method = FindMethod(h_klass, new_method_name, new_method_signature);
694 // If we got past the check for the same number of methods above that means there must be at
695 // least one added and one removed method. We will return the ADDED failure message since it is
696 // easier to get a useful error report for it.
697 if (old_method == nullptr) {
698 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_ADDED),
699 StringPrintf("Unknown method '%s' (sig: %s) was added!",
700 new_method_name,
701 new_method_signature.ToString().c_str()));
702 return false;
703 }
704 // Since direct methods have different flags than virtual ones (specifically direct methods must
705 // have kAccPrivate or kAccStatic or kAccConstructor flags) we can tell if a method changes from
706 // virtual to direct.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700707 uint32_t new_flags = method.GetAccessFlags();
Vladimir Markob0a6aee2017-10-27 10:34:04 +0100708 if (new_flags != (old_method->GetAccessFlags() & art::kAccValidMethodFlags)) {
Alex Light6161f132017-01-25 10:30:20 -0800709 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED),
710 StringPrintf("method '%s' (sig: %s) had different access flags",
711 new_method_name,
712 new_method_signature.ToString().c_str()));
713 return false;
714 }
715 }
716 return true;
717}
718
719bool Redefiner::ClassRedefinition::CheckSameFields() {
720 art::StackHandleScope<1> hs(driver_->self_);
721 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
722 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700723 art::ClassAccessor new_accessor(*dex_file_, dex_file_->GetClassDef(0));
724
Alex Light6161f132017-01-25 10:30:20 -0800725 const art::DexFile& old_dex_file = h_klass->GetDexFile();
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700726 art::ClassAccessor old_accessor(old_dex_file, *h_klass->GetClassDef());
Alex Light6161f132017-01-25 10:30:20 -0800727 // Instance and static fields can be differentiated by their flags so no need to check them
728 // separately.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700729 auto old_fields = old_accessor.GetFields();
730 auto old_iter = old_fields.begin();
731 for (const art::ClassAccessor::Field& new_field : new_accessor.GetFields()) {
Alex Light6161f132017-01-25 10:30:20 -0800732 // Get the data on the method we are searching for
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800733 const art::dex::FieldId& new_field_id = dex_file_->GetFieldId(new_field.GetIndex());
Alex Light6161f132017-01-25 10:30:20 -0800734 const char* new_field_name = dex_file_->GetFieldName(new_field_id);
735 const char* new_field_type = dex_file_->GetFieldTypeDescriptor(new_field_id);
736
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700737 if (old_iter == old_fields.end()) {
Alex Light6161f132017-01-25 10:30:20 -0800738 // We are missing the old version of this method!
739 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
740 StringPrintf("Unknown field '%s' (type: %s) added!",
741 new_field_name,
742 new_field_type));
743 return false;
744 }
745
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800746 const art::dex::FieldId& old_field_id = old_dex_file.GetFieldId(old_iter->GetIndex());
Alex Light6161f132017-01-25 10:30:20 -0800747 const char* old_field_name = old_dex_file.GetFieldName(old_field_id);
748 const char* old_field_type = old_dex_file.GetFieldTypeDescriptor(old_field_id);
749
750 // Check name and type.
751 if (strcmp(old_field_name, new_field_name) != 0 ||
752 strcmp(old_field_type, new_field_type) != 0) {
753 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
754 StringPrintf("Field changed from '%s' (sig: %s) to '%s' (sig: %s)!",
755 old_field_name,
756 old_field_type,
757 new_field_name,
758 new_field_type));
759 return false;
760 }
761
762 // Since static fields have different flags than instance ones (specifically static fields must
763 // have the kAccStatic flag) we can tell if a field changes from static to instance.
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700764 if (new_field.GetAccessFlags() != old_iter->GetAccessFlags()) {
Alex Light6161f132017-01-25 10:30:20 -0800765 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
766 StringPrintf("Field '%s' (sig: %s) had different access flags",
767 new_field_name,
768 new_field_type));
769 return false;
770 }
771
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700772 ++old_iter;
Alex Light6161f132017-01-25 10:30:20 -0800773 }
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700774 if (old_iter != old_fields.end()) {
Alex Light6161f132017-01-25 10:30:20 -0800775 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED),
776 StringPrintf("field '%s' (sig: %s) is missing!",
777 old_dex_file.GetFieldName(old_dex_file.GetFieldId(
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700778 old_iter->GetIndex())),
Alex Light6161f132017-01-25 10:30:20 -0800779 old_dex_file.GetFieldTypeDescriptor(old_dex_file.GetFieldId(
Mathieu Chartier4ac9ade2018-07-24 10:27:21 -0700780 old_iter->GetIndex()))));
Alex Light6161f132017-01-25 10:30:20 -0800781 return false;
782 }
783 return true;
784}
785
Alex Light0e692732017-01-10 15:00:05 -0800786bool Redefiner::ClassRedefinition::CheckClass() {
Alex Light0e692732017-01-10 15:00:05 -0800787 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000788 // Easy check that only 1 class def is present.
789 if (dex_file_->NumClassDefs() != 1) {
790 RecordFailure(ERR(ILLEGAL_ARGUMENT),
791 StringPrintf("Expected 1 class def in dex file but found %d",
792 dex_file_->NumClassDefs()));
793 return false;
794 }
795 // Get the ClassDef from the new DexFile.
796 // Since the dex file has only a single class def the index is always 0.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800797 const art::dex::ClassDef& def = dex_file_->GetClassDef(0);
Alex Light460d1b42017-01-10 15:37:17 +0000798 // Get the class as it is now.
799 art::Handle<art::mirror::Class> current_class(hs.NewHandle(GetMirrorClass()));
800
801 // Check the access flags didn't change.
802 if (def.GetJavaAccessFlags() != (current_class->GetAccessFlags() & art::kAccValidClassFlags)) {
803 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED),
804 "Cannot change modifiers of class by redefinition");
805 return false;
806 }
807
808 // Check class name.
809 // These should have been checked by the dexfile verifier on load.
810 DCHECK_NE(def.class_idx_, art::dex::TypeIndex::Invalid()) << "Invalid type index";
811 const char* descriptor = dex_file_->StringByTypeIdx(def.class_idx_);
812 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
813 if (!current_class->DescriptorEquals(descriptor)) {
814 std::string storage;
815 RecordFailure(ERR(NAMES_DONT_MATCH),
816 StringPrintf("expected file to contain class called '%s' but found '%s'!",
817 current_class->GetDescriptor(&storage),
818 descriptor));
819 return false;
820 }
821 if (current_class->IsObjectClass()) {
822 if (def.superclass_idx_ != art::dex::TypeIndex::Invalid()) {
823 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass added!");
824 return false;
825 }
826 } else {
827 const char* super_descriptor = dex_file_->StringByTypeIdx(def.superclass_idx_);
828 DCHECK(descriptor != nullptr) << "Invalid dex file structure!";
829 if (!current_class->GetSuperClass()->DescriptorEquals(super_descriptor)) {
830 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Superclass changed");
831 return false;
832 }
833 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800834 const art::dex::TypeList* interfaces = dex_file_->GetInterfacesList(def);
Alex Light460d1b42017-01-10 15:37:17 +0000835 if (interfaces == nullptr) {
836 if (current_class->NumDirectInterfaces() != 0) {
837 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added");
838 return false;
839 }
840 } else {
841 DCHECK(!current_class->IsProxyClass());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800842 const art::dex::TypeList* current_interfaces = current_class->GetInterfaceTypeList();
Alex Light460d1b42017-01-10 15:37:17 +0000843 if (current_interfaces == nullptr || current_interfaces->Size() != interfaces->Size()) {
844 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED), "Interfaces added or removed");
845 return false;
846 }
847 // The order of interfaces is (barely) meaningful so we error if it changes.
848 const art::DexFile& orig_dex_file = current_class->GetDexFile();
849 for (uint32_t i = 0; i < interfaces->Size(); i++) {
850 if (strcmp(
851 dex_file_->StringByTypeIdx(interfaces->GetTypeItem(i).type_idx_),
852 orig_dex_file.StringByTypeIdx(current_interfaces->GetTypeItem(i).type_idx_)) != 0) {
853 RecordFailure(ERR(UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED),
854 "Interfaces changed or re-ordered");
855 return false;
856 }
857 }
858 }
Alex Light460d1b42017-01-10 15:37:17 +0000859 return true;
860}
861
Alex Light0e692732017-01-10 15:00:05 -0800862bool Redefiner::ClassRedefinition::CheckRedefinable() {
Alex Lighte4a88632017-01-10 07:41:24 -0800863 std::string err;
Alex Light0e692732017-01-10 15:00:05 -0800864 art::StackHandleScope<1> hs(driver_->self_);
Alex Light460d1b42017-01-10 15:37:17 +0000865
Alex Lighte4a88632017-01-10 07:41:24 -0800866 art::Handle<art::mirror::Class> h_klass(hs.NewHandle(GetMirrorClass()));
867 jvmtiError res = Redefiner::GetClassRedefinitionError(h_klass, &err);
868 if (res != OK) {
869 RecordFailure(res, err);
870 return false;
871 } else {
872 return true;
873 }
Alex Light460d1b42017-01-10 15:37:17 +0000874}
875
Alex Light0e692732017-01-10 15:00:05 -0800876bool Redefiner::ClassRedefinition::CheckRedefinitionIsValid() {
Alex Light460d1b42017-01-10 15:37:17 +0000877 return CheckRedefinable() &&
878 CheckClass() &&
879 CheckSameFields() &&
880 CheckSameMethods();
881}
882
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800883class RedefinitionDataIter;
884
Alex Light0e692732017-01-10 15:00:05 -0800885// A wrapper that lets us hold onto the arbitrary sized data needed for redefinitions in a
886// reasonably sane way. This adds no fields to the normal ObjectArray. By doing this we can avoid
887// having to deal with the fact that we need to hold an arbitrary number of references live.
888class RedefinitionDataHolder {
889 public:
890 enum DataSlot : int32_t {
891 kSlotSourceClassLoader = 0,
892 kSlotJavaDexFile = 1,
893 kSlotNewDexFileCookie = 2,
894 kSlotNewDexCache = 3,
895 kSlotMirrorClass = 4,
Alex Lighta7e38d82017-01-19 14:57:28 -0800896 kSlotOrigDexFile = 5,
Alex Light1e3926a2017-04-07 10:38:06 -0700897 kSlotOldObsoleteMethods = 6,
898 kSlotOldDexCaches = 7,
Alex Light0e692732017-01-10 15:00:05 -0800899
900 // Must be last one.
Alex Light1e3926a2017-04-07 10:38:06 -0700901 kNumSlots = 8,
Alex Light0e692732017-01-10 15:00:05 -0800902 };
903
904 // This needs to have a HandleScope passed in that is capable of creating a new Handle without
905 // overflowing. Only one handle will be created. This object has a lifetime identical to that of
906 // the passed in handle-scope.
907 RedefinitionDataHolder(art::StackHandleScope<1>* hs,
908 art::Runtime* runtime,
909 art::Thread* self,
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800910 std::vector<Redefiner::ClassRedefinition>* redefinitions)
911 REQUIRES_SHARED(art::Locks::mutator_lock_) :
Vladimir Markob4eb1b12018-05-24 11:09:38 +0100912 arr_(hs->NewHandle(art::mirror::ObjectArray<art::mirror::Object>::Alloc(
913 self,
914 art::GetClassRoot<art::mirror::ObjectArray<art::mirror::Object>>(runtime->GetClassLinker()),
915 redefinitions->size() * kNumSlots))),
Alex Lightc5f5a6e2017-03-01 16:57:08 -0800916 redefinitions_(redefinitions) {}
Alex Light0e692732017-01-10 15:00:05 -0800917
918 bool IsNull() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
919 return arr_.IsNull();
920 }
921
Vladimir Markod93e3742018-07-18 10:58:13 +0100922 art::ObjPtr<art::mirror::ClassLoader> GetSourceClassLoader(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800923 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100924 return art::ObjPtr<art::mirror::ClassLoader>::DownCast(
925 GetSlot(klass_index, kSlotSourceClassLoader));
Alex Light0e692732017-01-10 15:00:05 -0800926 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100927 art::ObjPtr<art::mirror::Object> GetJavaDexFile(jint klass_index) const
Alex Light8c889d22017-02-06 13:58:27 -0800928 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800929 return GetSlot(klass_index, kSlotJavaDexFile);
930 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100931 art::ObjPtr<art::mirror::LongArray> GetNewDexFileCookie(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800932 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100933 return art::ObjPtr<art::mirror::LongArray>::DownCast(
934 GetSlot(klass_index, kSlotNewDexFileCookie));
Alex Light0e692732017-01-10 15:00:05 -0800935 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100936 art::ObjPtr<art::mirror::DexCache> GetNewDexCache(jint klass_index) const
Alex Light0e692732017-01-10 15:00:05 -0800937 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100938 return art::ObjPtr<art::mirror::DexCache>::DownCast(GetSlot(klass_index, kSlotNewDexCache));
Alex Light0e692732017-01-10 15:00:05 -0800939 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100940 art::ObjPtr<art::mirror::Class> GetMirrorClass(jint klass_index) const
Alex Light8c889d22017-02-06 13:58:27 -0800941 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100942 return art::ObjPtr<art::mirror::Class>::DownCast(GetSlot(klass_index, kSlotMirrorClass));
Alex Light0e692732017-01-10 15:00:05 -0800943 }
944
Vladimir Markod93e3742018-07-18 10:58:13 +0100945 art::ObjPtr<art::mirror::Object> GetOriginalDexFile(jint klass_index) const
Alex Lighta7e38d82017-01-19 14:57:28 -0800946 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100947 return art::ObjPtr<art::mirror::Object>::DownCast(GetSlot(klass_index, kSlotOrigDexFile));
Alex Lighta7e38d82017-01-19 14:57:28 -0800948 }
949
Vladimir Markod93e3742018-07-18 10:58:13 +0100950 art::ObjPtr<art::mirror::PointerArray> GetOldObsoleteMethods(jint klass_index) const
Alex Light1e3926a2017-04-07 10:38:06 -0700951 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Vladimir Markod93e3742018-07-18 10:58:13 +0100952 return art::ObjPtr<art::mirror::PointerArray>::DownCast(
Alex Light1e3926a2017-04-07 10:38:06 -0700953 GetSlot(klass_index, kSlotOldObsoleteMethods));
954 }
955
Vladimir Markod93e3742018-07-18 10:58:13 +0100956 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> GetOldDexCaches(
957 jint klass_index) const REQUIRES_SHARED(art::Locks::mutator_lock_) {
958 return art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>>::DownCast(
Alex Light1e3926a2017-04-07 10:38:06 -0700959 GetSlot(klass_index, kSlotOldDexCaches));
960 }
961
Vladimir Markod93e3742018-07-18 10:58:13 +0100962 void SetSourceClassLoader(jint klass_index, art::ObjPtr<art::mirror::ClassLoader> loader)
Alex Light0e692732017-01-10 15:00:05 -0800963 REQUIRES_SHARED(art::Locks::mutator_lock_) {
964 SetSlot(klass_index, kSlotSourceClassLoader, loader);
965 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100966 void SetJavaDexFile(jint klass_index, art::ObjPtr<art::mirror::Object> dexfile)
Alex Light0e692732017-01-10 15:00:05 -0800967 REQUIRES_SHARED(art::Locks::mutator_lock_) {
968 SetSlot(klass_index, kSlotJavaDexFile, dexfile);
969 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100970 void SetNewDexFileCookie(jint klass_index, art::ObjPtr<art::mirror::LongArray> cookie)
Alex Light0e692732017-01-10 15:00:05 -0800971 REQUIRES_SHARED(art::Locks::mutator_lock_) {
972 SetSlot(klass_index, kSlotNewDexFileCookie, cookie);
973 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100974 void SetNewDexCache(jint klass_index, art::ObjPtr<art::mirror::DexCache> cache)
Alex Light0e692732017-01-10 15:00:05 -0800975 REQUIRES_SHARED(art::Locks::mutator_lock_) {
976 SetSlot(klass_index, kSlotNewDexCache, cache);
977 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100978 void SetMirrorClass(jint klass_index, art::ObjPtr<art::mirror::Class> klass)
Alex Light0e692732017-01-10 15:00:05 -0800979 REQUIRES_SHARED(art::Locks::mutator_lock_) {
980 SetSlot(klass_index, kSlotMirrorClass, klass);
981 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100982 void SetOriginalDexFile(jint klass_index, art::ObjPtr<art::mirror::Object> bytes)
Alex Lighta7e38d82017-01-19 14:57:28 -0800983 REQUIRES_SHARED(art::Locks::mutator_lock_) {
984 SetSlot(klass_index, kSlotOrigDexFile, bytes);
985 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100986 void SetOldObsoleteMethods(jint klass_index, art::ObjPtr<art::mirror::PointerArray> methods)
Alex Light1e3926a2017-04-07 10:38:06 -0700987 REQUIRES_SHARED(art::Locks::mutator_lock_) {
988 SetSlot(klass_index, kSlotOldObsoleteMethods, methods);
989 }
Vladimir Markod93e3742018-07-18 10:58:13 +0100990 void SetOldDexCaches(jint klass_index,
991 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)
Alex Light1e3926a2017-04-07 10:38:06 -0700992 REQUIRES_SHARED(art::Locks::mutator_lock_) {
993 SetSlot(klass_index, kSlotOldDexCaches, caches);
994 }
Alex Light0e692732017-01-10 15:00:05 -0800995
Alex Light8c889d22017-02-06 13:58:27 -0800996 int32_t Length() const REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -0800997 return arr_->GetLength() / kNumSlots;
998 }
999
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001000 std::vector<Redefiner::ClassRedefinition>* GetRedefinitions()
1001 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1002 return redefinitions_;
1003 }
1004
1005 bool operator==(const RedefinitionDataHolder& other) const
1006 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1007 return arr_.Get() == other.arr_.Get();
1008 }
1009
1010 bool operator!=(const RedefinitionDataHolder& other) const
1011 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1012 return !(*this == other);
1013 }
1014
1015 RedefinitionDataIter begin() REQUIRES_SHARED(art::Locks::mutator_lock_);
1016 RedefinitionDataIter end() REQUIRES_SHARED(art::Locks::mutator_lock_);
1017
Alex Light0e692732017-01-10 15:00:05 -08001018 private:
Alex Light8c889d22017-02-06 13:58:27 -08001019 mutable art::Handle<art::mirror::ObjectArray<art::mirror::Object>> arr_;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001020 std::vector<Redefiner::ClassRedefinition>* redefinitions_;
Alex Light0e692732017-01-10 15:00:05 -08001021
Vladimir Markod93e3742018-07-18 10:58:13 +01001022 art::ObjPtr<art::mirror::Object> GetSlot(jint klass_index, DataSlot slot) const
1023 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light0e692732017-01-10 15:00:05 -08001024 DCHECK_LT(klass_index, Length());
1025 return arr_->Get((kNumSlots * klass_index) + slot);
1026 }
1027
1028 void SetSlot(jint klass_index,
1029 DataSlot slot,
1030 art::ObjPtr<art::mirror::Object> obj) REQUIRES_SHARED(art::Locks::mutator_lock_) {
1031 DCHECK(!art::Runtime::Current()->IsActiveTransaction());
1032 DCHECK_LT(klass_index, Length());
1033 arr_->Set<false>((kNumSlots * klass_index) + slot, obj);
1034 }
1035
1036 DISALLOW_COPY_AND_ASSIGN(RedefinitionDataHolder);
1037};
1038
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001039class RedefinitionDataIter {
1040 public:
1041 RedefinitionDataIter(int32_t idx, RedefinitionDataHolder& holder) : idx_(idx), holder_(holder) {}
1042
1043 RedefinitionDataIter(const RedefinitionDataIter&) = default;
1044 RedefinitionDataIter(RedefinitionDataIter&&) = default;
1045 RedefinitionDataIter& operator=(const RedefinitionDataIter&) = default;
1046 RedefinitionDataIter& operator=(RedefinitionDataIter&&) = default;
1047
1048 bool operator==(const RedefinitionDataIter& other) const
1049 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1050 return idx_ == other.idx_ && holder_ == other.holder_;
1051 }
1052
1053 bool operator!=(const RedefinitionDataIter& other) const
1054 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1055 return !(*this == other);
1056 }
1057
1058 RedefinitionDataIter operator++() { // Value after modification.
1059 idx_++;
1060 return *this;
1061 }
1062
1063 RedefinitionDataIter operator++(int) {
1064 RedefinitionDataIter temp = *this;
1065 idx_++;
1066 return temp;
1067 }
1068
1069 RedefinitionDataIter operator+(ssize_t delta) const {
1070 RedefinitionDataIter temp = *this;
1071 temp += delta;
1072 return temp;
1073 }
1074
1075 RedefinitionDataIter& operator+=(ssize_t delta) {
1076 idx_ += delta;
1077 return *this;
1078 }
1079
1080 Redefiner::ClassRedefinition& GetRedefinition() REQUIRES_SHARED(art::Locks::mutator_lock_) {
1081 return (*holder_.GetRedefinitions())[idx_];
1082 }
1083
1084 RedefinitionDataHolder& GetHolder() {
1085 return holder_;
1086 }
1087
Vladimir Markod93e3742018-07-18 10:58:13 +01001088 art::ObjPtr<art::mirror::ClassLoader> GetSourceClassLoader() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001089 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1090 return holder_.GetSourceClassLoader(idx_);
1091 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001092 art::ObjPtr<art::mirror::Object> GetJavaDexFile() const
1093 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001094 return holder_.GetJavaDexFile(idx_);
1095 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001096 art::ObjPtr<art::mirror::LongArray> GetNewDexFileCookie() const
1097 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001098 return holder_.GetNewDexFileCookie(idx_);
1099 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001100 art::ObjPtr<art::mirror::DexCache> GetNewDexCache() const
1101 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001102 return holder_.GetNewDexCache(idx_);
1103 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001104 art::ObjPtr<art::mirror::Class> GetMirrorClass() const
1105 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001106 return holder_.GetMirrorClass(idx_);
1107 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001108 art::ObjPtr<art::mirror::Object> GetOriginalDexFile() const
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001109 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001110 return holder_.GetOriginalDexFile(idx_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001111 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001112 art::ObjPtr<art::mirror::PointerArray> GetOldObsoleteMethods() const
Alex Light1e3926a2017-04-07 10:38:06 -07001113 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1114 return holder_.GetOldObsoleteMethods(idx_);
1115 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001116 art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> GetOldDexCaches() const
Alex Light1e3926a2017-04-07 10:38:06 -07001117 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1118 return holder_.GetOldDexCaches(idx_);
1119 }
1120
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001121 int32_t GetIndex() const {
1122 return idx_;
1123 }
1124
1125 void SetSourceClassLoader(art::mirror::ClassLoader* loader)
1126 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1127 holder_.SetSourceClassLoader(idx_, loader);
1128 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001129 void SetJavaDexFile(art::ObjPtr<art::mirror::Object> dexfile)
1130 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001131 holder_.SetJavaDexFile(idx_, dexfile);
1132 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001133 void SetNewDexFileCookie(art::ObjPtr<art::mirror::LongArray> cookie)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001134 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1135 holder_.SetNewDexFileCookie(idx_, cookie);
1136 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001137 void SetNewDexCache(art::ObjPtr<art::mirror::DexCache> cache)
1138 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001139 holder_.SetNewDexCache(idx_, cache);
1140 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001141 void SetMirrorClass(art::ObjPtr<art::mirror::Class> klass)
1142 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001143 holder_.SetMirrorClass(idx_, klass);
1144 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001145 void SetOriginalDexFile(art::ObjPtr<art::mirror::Object> bytes)
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001146 REQUIRES_SHARED(art::Locks::mutator_lock_) {
Alex Light2f814aa2017-03-24 15:21:34 +00001147 holder_.SetOriginalDexFile(idx_, bytes);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001148 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001149 void SetOldObsoleteMethods(art::ObjPtr<art::mirror::PointerArray> methods)
Alex Light1e3926a2017-04-07 10:38:06 -07001150 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1151 holder_.SetOldObsoleteMethods(idx_, methods);
1152 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001153 void SetOldDexCaches(art::ObjPtr<art::mirror::ObjectArray<art::mirror::DexCache>> caches)
Alex Light1e3926a2017-04-07 10:38:06 -07001154 REQUIRES_SHARED(art::Locks::mutator_lock_) {
1155 holder_.SetOldDexCaches(idx_, caches);
1156 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001157
1158 private:
1159 int32_t idx_;
1160 RedefinitionDataHolder& holder_;
1161};
1162
1163RedefinitionDataIter RedefinitionDataHolder::begin() {
1164 return RedefinitionDataIter(0, *this);
1165}
1166
1167RedefinitionDataIter RedefinitionDataHolder::end() {
1168 return RedefinitionDataIter(Length(), *this);
1169}
1170
1171bool Redefiner::ClassRedefinition::CheckVerification(const RedefinitionDataIter& iter) {
Alex Light8c889d22017-02-06 13:58:27 -08001172 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
1173 art::StackHandleScope<2> hs(driver_->self_);
1174 std::string error;
1175 // TODO Make verification log level lower
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07001176 art::verifier::FailureKind failure =
Andreas Gampea43ba3d2019-03-13 15:49:20 -07001177 art::verifier::ClassVerifier::VerifyClass(driver_->self_,
1178 dex_file_.get(),
1179 hs.NewHandle(iter.GetNewDexCache()),
1180 hs.NewHandle(GetClassLoader()),
1181 /*class_def=*/ dex_file_->GetClassDef(0),
1182 /*callbacks=*/ nullptr,
1183 /*allow_soft_failures=*/ true,
1184 /*log_level=*/
1185 art::verifier::HardFailLogMode::kLogWarning,
1186 art::Runtime::Current()->GetTargetSdkVersion(),
1187 &error);
Alex Light53330612017-10-04 15:29:53 -07001188 switch (failure) {
1189 case art::verifier::FailureKind::kNoFailure:
1190 case art::verifier::FailureKind::kSoftFailure:
1191 return true;
1192 case art::verifier::FailureKind::kHardFailure: {
1193 RecordFailure(ERR(FAILS_VERIFICATION), "Failed to verify class. Error was: " + error);
1194 return false;
1195 }
Alex Light8c889d22017-02-06 13:58:27 -08001196 }
Alex Light8c889d22017-02-06 13:58:27 -08001197}
1198
Alex Light1babae02017-02-01 15:35:34 -08001199// Looks through the previously allocated cookies to see if we need to update them with another new
1200// dexfile. This is so that even if multiple classes with the same classloader are redefined at
1201// once they are all added to the classloader.
1202bool Redefiner::ClassRedefinition::AllocateAndRememberNewDexFileCookie(
Alex Light1babae02017-02-01 15:35:34 -08001203 art::Handle<art::mirror::ClassLoader> source_class_loader,
1204 art::Handle<art::mirror::Object> dex_file_obj,
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001205 /*out*/RedefinitionDataIter* cur_data) {
Alex Light1babae02017-02-01 15:35:34 -08001206 art::StackHandleScope<2> hs(driver_->self_);
1207 art::MutableHandle<art::mirror::LongArray> old_cookie(
1208 hs.NewHandle<art::mirror::LongArray>(nullptr));
1209 bool has_older_cookie = false;
1210 // See if we already have a cookie that a previous redefinition got from the same classloader.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001211 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
1212 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
Alex Light1babae02017-02-01 15:35:34 -08001213 // Since every instance of this classloader should have the same cookie associated with it we
1214 // can stop looking here.
1215 has_older_cookie = true;
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001216 old_cookie.Assign(old_data.GetNewDexFileCookie());
Alex Light1babae02017-02-01 15:35:34 -08001217 break;
1218 }
1219 }
1220 if (old_cookie.IsNull()) {
1221 // No older cookie. Get it directly from the dex_file_obj
1222 // We should not have seen this classloader elsewhere.
1223 CHECK(!has_older_cookie);
1224 old_cookie.Assign(ClassLoaderHelper::GetDexFileCookie(dex_file_obj));
1225 }
1226 // Use the old cookie to generate the new one with the new DexFile* added in.
1227 art::Handle<art::mirror::LongArray>
1228 new_cookie(hs.NewHandle(ClassLoaderHelper::AllocateNewDexFileCookie(driver_->self_,
1229 old_cookie,
1230 dex_file_.get())));
1231 // Make sure the allocation worked.
1232 if (new_cookie.IsNull()) {
1233 return false;
1234 }
1235
1236 // Save the cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001237 cur_data->SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001238 // If there are other copies of this same classloader we need to make sure that we all have the
1239 // same cookie.
1240 if (has_older_cookie) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001241 for (auto old_data = cur_data->GetHolder().begin(); old_data != *cur_data; ++old_data) {
Alex Light1babae02017-02-01 15:35:34 -08001242 // We will let the GC take care of the cookie we allocated for this one.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001243 if (old_data.GetSourceClassLoader() == source_class_loader.Get()) {
1244 old_data.SetNewDexFileCookie(new_cookie.Get());
Alex Light1babae02017-02-01 15:35:34 -08001245 }
1246 }
1247 }
1248
1249 return true;
1250}
1251
Alex Lighta7e38d82017-01-19 14:57:28 -08001252bool Redefiner::ClassRedefinition::FinishRemainingAllocations(
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001253 /*out*/RedefinitionDataIter* cur_data) {
Alex Light7916f202017-01-27 09:00:15 -08001254 art::ScopedObjectAccessUnchecked soa(driver_->self_);
Alex Lighta7e38d82017-01-19 14:57:28 -08001255 art::StackHandleScope<2> hs(driver_->self_);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001256 cur_data->SetMirrorClass(GetMirrorClass());
Alex Lighta7e38d82017-01-19 14:57:28 -08001257 // This shouldn't allocate
1258 art::Handle<art::mirror::ClassLoader> loader(hs.NewHandle(GetClassLoader()));
Alex Light7916f202017-01-27 09:00:15 -08001259 // The bootclasspath is handled specially so it doesn't have a j.l.DexFile.
1260 if (!art::ClassLinker::IsBootClassLoader(soa, loader.Get())) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001261 cur_data->SetSourceClassLoader(loader.Get());
Alex Light7916f202017-01-27 09:00:15 -08001262 art::Handle<art::mirror::Object> dex_file_obj(hs.NewHandle(
1263 ClassLoaderHelper::FindSourceDexFileObject(driver_->self_, loader)));
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001264 cur_data->SetJavaDexFile(dex_file_obj.Get());
Andreas Gampefa4333d2017-02-14 11:10:34 -08001265 if (dex_file_obj == nullptr) {
Alex Light7916f202017-01-27 09:00:15 -08001266 RecordFailure(ERR(INTERNAL), "Unable to find dex file!");
1267 return false;
1268 }
Alex Light1babae02017-02-01 15:35:34 -08001269 // Allocate the new dex file cookie.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001270 if (!AllocateAndRememberNewDexFileCookie(loader, dex_file_obj, cur_data)) {
Alex Light7916f202017-01-27 09:00:15 -08001271 driver_->self_->AssertPendingOOMException();
1272 driver_->self_->ClearException();
1273 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate dex file array for class loader");
1274 return false;
1275 }
Alex Lighta7e38d82017-01-19 14:57:28 -08001276 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001277 cur_data->SetNewDexCache(CreateNewDexCache(loader));
1278 if (cur_data->GetNewDexCache() == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00001279 driver_->self_->AssertPendingException();
Alex Lighta7e38d82017-01-19 14:57:28 -08001280 driver_->self_->ClearException();
1281 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate DexCache");
1282 return false;
1283 }
1284
1285 // We won't always need to set this field.
Alex Light2f814aa2017-03-24 15:21:34 +00001286 cur_data->SetOriginalDexFile(AllocateOrGetOriginalDexFile());
1287 if (cur_data->GetOriginalDexFile() == nullptr) {
Alex Lighta7e38d82017-01-19 14:57:28 -08001288 driver_->self_->AssertPendingOOMException();
1289 driver_->self_->ClearException();
1290 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate array for original dex file");
1291 return false;
1292 }
1293 return true;
1294}
1295
Alex Lighta26e3492017-06-27 17:55:37 -07001296void Redefiner::ClassRedefinition::UnregisterJvmtiBreakpoints() {
Vladimir Marko4617d582019-03-28 13:48:31 +00001297 BreakpointUtil::RemoveBreakpointsInClass(driver_->env_, GetMirrorClass().Ptr());
Alex Lighta26e3492017-06-27 17:55:37 -07001298}
1299
Alex Light5643caf2017-02-08 11:39:07 -08001300void Redefiner::ClassRedefinition::UnregisterBreakpoints() {
Alex Lighte34fe442018-02-21 17:35:55 -08001301 if (LIKELY(!art::Dbg::IsDebuggerActive())) {
1302 return;
1303 }
Alex Light5643caf2017-02-08 11:39:07 -08001304 art::JDWP::JdwpState* state = art::Dbg::GetJdwpState();
1305 if (state != nullptr) {
1306 state->UnregisterLocationEventsOnClass(GetMirrorClass());
1307 }
1308}
1309
1310void Redefiner::UnregisterAllBreakpoints() {
Alex Light5643caf2017-02-08 11:39:07 -08001311 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1312 redef.UnregisterBreakpoints();
Alex Lighte34fe442018-02-21 17:35:55 -08001313 redef.UnregisterJvmtiBreakpoints();
Alex Light5643caf2017-02-08 11:39:07 -08001314 }
1315}
1316
Alex Light0e692732017-01-10 15:00:05 -08001317bool Redefiner::CheckAllRedefinitionAreValid() {
1318 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1319 if (!redef.CheckRedefinitionIsValid()) {
1320 return false;
1321 }
1322 }
1323 return true;
1324}
1325
Alex Light1e3926a2017-04-07 10:38:06 -07001326void Redefiner::RestoreObsoleteMethodMapsIfUnneeded(RedefinitionDataHolder& holder) {
1327 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1328 data.GetRedefinition().RestoreObsoleteMethodMapsIfUnneeded(&data);
1329 }
1330}
1331
1332bool Redefiner::EnsureAllClassAllocationsFinished(RedefinitionDataHolder& holder) {
1333 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1334 if (!data.GetRedefinition().EnsureClassAllocationsFinished(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001335 return false;
1336 }
1337 }
1338 return true;
1339}
1340
1341bool Redefiner::FinishAllRemainingAllocations(RedefinitionDataHolder& holder) {
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001342 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light0e692732017-01-10 15:00:05 -08001343 // Allocate the data this redefinition requires.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001344 if (!data.GetRedefinition().FinishRemainingAllocations(&data)) {
Alex Light0e692732017-01-10 15:00:05 -08001345 return false;
1346 }
Alex Light0e692732017-01-10 15:00:05 -08001347 }
1348 return true;
1349}
1350
1351void Redefiner::ClassRedefinition::ReleaseDexFile() {
Andreas Gampeafaf7f82018-10-16 11:32:38 -07001352 dex_file_.release(); // NOLINT b/117926937
Alex Light0e692732017-01-10 15:00:05 -08001353}
1354
1355void Redefiner::ReleaseAllDexFiles() {
1356 for (Redefiner::ClassRedefinition& redef : redefinitions_) {
1357 redef.ReleaseDexFile();
1358 }
1359}
1360
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001361bool Redefiner::CheckAllClassesAreVerified(RedefinitionDataHolder& holder) {
1362 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
1363 if (!data.GetRedefinition().CheckVerification(data)) {
Alex Light8c889d22017-02-06 13:58:27 -08001364 return false;
1365 }
Alex Light8c889d22017-02-06 13:58:27 -08001366 }
1367 return true;
1368}
1369
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001370class ScopedDisableConcurrentAndMovingGc {
1371 public:
1372 ScopedDisableConcurrentAndMovingGc(art::gc::Heap* heap, art::Thread* self)
1373 : heap_(heap), self_(self) {
1374 if (heap_->IsGcConcurrentAndMoving()) {
1375 heap_->IncrementDisableMovingGC(self_);
1376 }
1377 }
1378
1379 ~ScopedDisableConcurrentAndMovingGc() {
1380 if (heap_->IsGcConcurrentAndMoving()) {
1381 heap_->DecrementDisableMovingGC(self_);
1382 }
1383 }
1384 private:
1385 art::gc::Heap* heap_;
1386 art::Thread* self_;
1387};
1388
Alex Lighta01de592016-11-15 10:43:06 -08001389jvmtiError Redefiner::Run() {
Alex Light0e692732017-01-10 15:00:05 -08001390 art::StackHandleScope<1> hs(self_);
1391 // Allocate an array to hold onto all java temporary objects associated with this redefinition.
1392 // We will let this be collected after the end of this function.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001393 RedefinitionDataHolder holder(&hs, runtime_, self_, &redefinitions_);
Alex Light0e692732017-01-10 15:00:05 -08001394 if (holder.IsNull()) {
1395 self_->AssertPendingOOMException();
1396 self_->ClearException();
1397 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate storage for temporaries");
1398 return result_;
1399 }
1400
Alex Lighta01de592016-11-15 10:43:06 -08001401 // First we just allocate the ClassExt and its fields that we need. These can be updated
1402 // atomically without any issues (since we allocate the map arrays as empty) so we don't bother
1403 // doing a try loop. The other allocations we need to ensure that nothing has changed in the time
1404 // between allocating them and pausing all threads before we can update them so we need to do a
1405 // try loop.
Alex Light0e692732017-01-10 15:00:05 -08001406 if (!CheckAllRedefinitionAreValid() ||
Alex Light1e3926a2017-04-07 10:38:06 -07001407 !EnsureAllClassAllocationsFinished(holder) ||
Alex Light8c889d22017-02-06 13:58:27 -08001408 !FinishAllRemainingAllocations(holder) ||
1409 !CheckAllClassesAreVerified(holder)) {
Alex Lighta01de592016-11-15 10:43:06 -08001410 return result_;
1411 }
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001412
Alex Light5643caf2017-02-08 11:39:07 -08001413 // At this point we can no longer fail without corrupting the runtime state.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001414 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Light07f06212017-06-01 14:01:43 -07001415 art::ClassLinker* cl = runtime_->GetClassLinker();
1416 cl->RegisterExistingDexCache(data.GetNewDexCache(), data.GetSourceClassLoader());
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001417 if (data.GetSourceClassLoader() == nullptr) {
Alex Light07f06212017-06-01 14:01:43 -07001418 cl->AppendToBootClassPath(self_, data.GetRedefinition().GetDexFile());
Alex Light7916f202017-01-27 09:00:15 -08001419 }
Alex Light7916f202017-01-27 09:00:15 -08001420 }
Alex Light5643caf2017-02-08 11:39:07 -08001421 UnregisterAllBreakpoints();
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001422
Alex Light6abd5392017-01-05 17:53:00 -08001423 // Disable GC and wait for it to be done if we are a moving GC. This is fine since we are done
1424 // allocating so no deadlocks.
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001425 ScopedDisableConcurrentAndMovingGc sdcamgc(runtime_->GetHeap(), self_);
1426
Alex Lighta01de592016-11-15 10:43:06 -08001427 // Do transition to final suspension
1428 // TODO We might want to give this its own suspended state!
1429 // TODO This isn't right. We need to change state without any chance of suspend ideally!
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001430 art::ScopedThreadSuspension sts(self_, art::ThreadState::kNative);
Andreas Gampe6e897762018-10-16 13:09:32 -07001431 art::ScopedSuspendAll ssa("Final installation of redefined Classes!", /*long_suspend=*/true);
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001432 for (RedefinitionDataIter data = holder.begin(); data != holder.end(); ++data) {
Alex Lighteb98b082017-01-25 13:02:32 -08001433 art::ScopedAssertNoThreadSuspension nts("Updating runtime objects for redefinition");
Alex Lightc5f5a6e2017-03-01 16:57:08 -08001434 ClassRedefinition& redef = data.GetRedefinition();
1435 if (data.GetSourceClassLoader() != nullptr) {
1436 ClassLoaderHelper::UpdateJavaDexFile(data.GetJavaDexFile(), data.GetNewDexFileCookie());
Alex Light7916f202017-01-27 09:00:15 -08001437 }
Vladimir Markod93e3742018-07-18 10:58:13 +01001438 art::ObjPtr<art::mirror::Class> klass = data.GetMirrorClass();
Alex Light0e692732017-01-10 15:00:05 -08001439 // TODO Rewrite so we don't do a stack walk for each and every class.
1440 redef.FindAndAllocateObsoleteMethods(klass);
Alex Light2f814aa2017-03-24 15:21:34 +00001441 redef.UpdateClass(klass, data.GetNewDexCache(), data.GetOriginalDexFile());
Alex Light0e692732017-01-10 15:00:05 -08001442 }
Alex Light1e3926a2017-04-07 10:38:06 -07001443 RestoreObsoleteMethodMapsIfUnneeded(holder);
Alex Light7532d582017-02-13 16:36:06 -08001444 // TODO We should check for if any of the redefined methods are intrinsic methods here and, if any
1445 // are, force a full-world deoptimization before finishing redefinition. If we don't do this then
1446 // methods that have been jitted prior to the current redefinition being applied might continue
1447 // to use the old versions of the intrinsics!
Alex Light0e692732017-01-10 15:00:05 -08001448 // TODO Do the dex_file release at a more reasonable place. This works but it muddles who really
1449 // owns the DexFile and when ownership is transferred.
1450 ReleaseAllDexFiles();
Alex Lighta01de592016-11-15 10:43:06 -08001451 return OK;
1452}
1453
Alex Light0e692732017-01-10 15:00:05 -08001454void Redefiner::ClassRedefinition::UpdateMethods(art::ObjPtr<art::mirror::Class> mclass,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001455 const art::dex::ClassDef& class_def) {
Alex Light0e692732017-01-10 15:00:05 -08001456 art::ClassLinker* linker = driver_->runtime_->GetClassLinker();
Alex Lighta01de592016-11-15 10:43:06 -08001457 art::PointerSize image_pointer_size = linker->GetImagePointerSize();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001458 const art::dex::TypeId& declaring_class_id = dex_file_->GetTypeId(class_def.class_idx_);
Alex Lighta01de592016-11-15 10:43:06 -08001459 const art::DexFile& old_dex_file = mclass->GetDexFile();
Alex Light200b9d72016-12-15 11:34:13 -08001460 // Update methods.
Alex Light00e475c2017-07-19 16:36:23 -07001461 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001462 const art::dex::StringId* new_name_id = dex_file_->FindStringId(method.GetName());
Alex Lighta01de592016-11-15 10:43:06 -08001463 art::dex::TypeIndex method_return_idx =
1464 dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(method.GetReturnTypeDescriptor()));
1465 const auto* old_type_list = method.GetParameterTypeList();
1466 std::vector<art::dex::TypeIndex> new_type_list;
1467 for (uint32_t i = 0; old_type_list != nullptr && i < old_type_list->Size(); i++) {
1468 new_type_list.push_back(
1469 dex_file_->GetIndexForTypeId(
1470 *dex_file_->FindTypeId(
1471 old_dex_file.GetTypeDescriptor(
1472 old_dex_file.GetTypeId(
1473 old_type_list->GetTypeItem(i).type_idx_)))));
1474 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001475 const art::dex::ProtoId* proto_id = dex_file_->FindProtoId(method_return_idx, new_type_list);
Alex Lightdba61482016-12-21 08:20:29 -08001476 CHECK(proto_id != nullptr || old_type_list == nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001477 const art::dex::MethodId* method_id = dex_file_->FindMethodId(declaring_class_id,
1478 *new_name_id,
1479 *proto_id);
Alex Lightdba61482016-12-21 08:20:29 -08001480 CHECK(method_id != nullptr);
Alex Lighta01de592016-11-15 10:43:06 -08001481 uint32_t dex_method_idx = dex_file_->GetIndexForMethodId(*method_id);
1482 method.SetDexMethodIndex(dex_method_idx);
1483 linker->SetEntryPointsToInterpreter(&method);
Alex Light200b9d72016-12-15 11:34:13 -08001484 method.SetCodeItemOffset(dex_file_->FindCodeItemOffset(class_def, dex_method_idx));
Alex Light7532d582017-02-13 16:36:06 -08001485 // Clear all the intrinsics related flags.
Orion Hodsoncfcc9cf2017-09-29 15:07:27 +01001486 method.SetNotIntrinsic();
Alex Lighta01de592016-11-15 10:43:06 -08001487 }
Alex Light200b9d72016-12-15 11:34:13 -08001488}
1489
Alex Light0e692732017-01-10 15:00:05 -08001490void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> mclass) {
Alex Light200b9d72016-12-15 11:34:13 -08001491 // TODO The IFields & SFields pointers should be combined like the methods_ arrays were.
1492 for (auto fields_iter : {mclass->GetIFields(), mclass->GetSFields()}) {
1493 for (art::ArtField& field : fields_iter) {
1494 std::string declaring_class_name;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001495 const art::dex::TypeId* new_declaring_id =
Alex Light200b9d72016-12-15 11:34:13 -08001496 dex_file_->FindTypeId(field.GetDeclaringClass()->GetDescriptor(&declaring_class_name));
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001497 const art::dex::StringId* new_name_id = dex_file_->FindStringId(field.GetName());
1498 const art::dex::TypeId* new_type_id = dex_file_->FindTypeId(field.GetTypeDescriptor());
Alex Light200b9d72016-12-15 11:34:13 -08001499 CHECK(new_name_id != nullptr && new_type_id != nullptr && new_declaring_id != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001500 const art::dex::FieldId* new_field_id =
Alex Light200b9d72016-12-15 11:34:13 -08001501 dex_file_->FindFieldId(*new_declaring_id, *new_name_id, *new_type_id);
1502 CHECK(new_field_id != nullptr);
1503 // We only need to update the index since the other data in the ArtField cannot be updated.
1504 field.SetDexFieldIndex(dex_file_->GetIndexForFieldId(*new_field_id));
1505 }
1506 }
Alex Light200b9d72016-12-15 11:34:13 -08001507}
1508
1509// Performs updates to class that will allow us to verify it.
Alex Lighta7e38d82017-01-19 14:57:28 -08001510void Redefiner::ClassRedefinition::UpdateClass(
1511 art::ObjPtr<art::mirror::Class> mclass,
1512 art::ObjPtr<art::mirror::DexCache> new_dex_cache,
Alex Light2f814aa2017-03-24 15:21:34 +00001513 art::ObjPtr<art::mirror::Object> original_dex_file) {
Alex Light6ac57502017-01-19 15:05:06 -08001514 DCHECK_EQ(dex_file_->NumClassDefs(), 1u);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08001515 const art::dex::ClassDef& class_def = dex_file_->GetClassDef(0);
Vladimir Marko5122e6b2017-08-17 16:10:09 +01001516 UpdateMethods(mclass, class_def);
Alex Light007ada22017-01-10 13:33:56 -08001517 UpdateFields(mclass);
Alex Light200b9d72016-12-15 11:34:13 -08001518
David Brazdil1a658632018-12-01 17:54:26 +00001519 art::ObjPtr<art::mirror::ClassExt> ext(mclass->GetExtData());
1520 CHECK(!ext.IsNull());
1521 ext->SetOriginalDexFile(original_dex_file);
1522
1523 // If this is the first time the class is being redefined, store
1524 // the native DexFile pointer and initial ClassDef index in ClassExt.
1525 // This preserves the pointer for hiddenapi access checks which need
1526 // to read access flags from the initial DexFile.
1527 if (ext->GetPreRedefineDexFile() == nullptr) {
1528 ext->SetPreRedefineDexFile(&mclass->GetDexFile());
1529 ext->SetPreRedefineClassDefIndex(mclass->GetDexClassDefIndex());
1530 }
1531
Alex Lighta01de592016-11-15 10:43:06 -08001532 // Update the class fields.
1533 // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed
1534 // to call GetReturnTypeDescriptor and GetParameterTypeList above).
1535 mclass->SetDexCache(new_dex_cache.Ptr());
Alex Light6ac57502017-01-19 15:05:06 -08001536 mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def));
Alex Light0e692732017-01-10 15:00:05 -08001537 mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str())));
Alex Light035105f2018-03-05 17:48:48 -08001538
1539 // Notify the jit that all the methods in this class were redefined. Need to do this last since
1540 // the jit relies on the dex_file_ being correct (for native methods at least) to find the method
1541 // meta-data.
1542 art::jit::Jit* jit = driver_->runtime_->GetJit();
1543 if (jit != nullptr) {
1544 art::PointerSize image_pointer_size =
1545 driver_->runtime_->GetClassLinker()->GetImagePointerSize();
1546 auto code_cache = jit->GetCodeCache();
1547 // Non-invokable methods don't have any JIT data associated with them so we don't need to tell
1548 // the jit about them.
1549 for (art::ArtMethod& method : mclass->GetDeclaredMethods(image_pointer_size)) {
1550 if (method.IsInvokable()) {
1551 code_cache->NotifyMethodRedefined(&method);
1552 }
1553 }
1554 }
Alex Lighta01de592016-11-15 10:43:06 -08001555}
1556
Alex Light1e3926a2017-04-07 10:38:06 -07001557// Restores the old obsolete methods maps if it turns out they weren't needed (ie there were no new
1558// obsolete methods).
1559void Redefiner::ClassRedefinition::RestoreObsoleteMethodMapsIfUnneeded(
1560 const RedefinitionDataIter* cur_data) {
Vladimir Markod93e3742018-07-18 10:58:13 +01001561 art::ObjPtr<art::mirror::Class> klass = GetMirrorClass();
1562 art::ObjPtr<art::mirror::ClassExt> ext = klass->GetExtData();
1563 art::ObjPtr<art::mirror::PointerArray> methods = ext->GetObsoleteMethods();
1564 art::ObjPtr<art::mirror::PointerArray> old_methods = cur_data->GetOldObsoleteMethods();
Alex Light70713df2017-04-18 13:03:31 -07001565 int32_t old_length = old_methods == nullptr ? 0 : old_methods->GetLength();
Alex Light1e3926a2017-04-07 10:38:06 -07001566 int32_t expected_length =
1567 old_length + klass->NumDirectMethods() + klass->NumDeclaredVirtualMethods();
1568 // Check to make sure we are only undoing this one.
1569 if (expected_length == methods->GetLength()) {
Alex Light70713df2017-04-18 13:03:31 -07001570 for (int32_t i = 0; i < expected_length; i++) {
1571 art::ArtMethod* expected = nullptr;
1572 if (i < old_length) {
1573 expected = old_methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize);
1574 }
1575 if (methods->GetElementPtrSize<art::ArtMethod*>(i, art::kRuntimePointerSize) != expected) {
Alex Light1e3926a2017-04-07 10:38:06 -07001576 // We actually have some new obsolete methods. Just abort since we cannot safely shrink the
1577 // obsolete methods array.
1578 return;
1579 }
1580 }
1581 // No new obsolete methods! We can get rid of the maps.
1582 ext->SetObsoleteArrays(cur_data->GetOldObsoleteMethods(), cur_data->GetOldDexCaches());
1583 }
1584}
1585
Alex Lighta01de592016-11-15 10:43:06 -08001586// This function does all (java) allocations we need to do for the Class being redefined.
1587// TODO Change this name maybe?
Alex Light1e3926a2017-04-07 10:38:06 -07001588bool Redefiner::ClassRedefinition::EnsureClassAllocationsFinished(
1589 /*out*/RedefinitionDataIter* cur_data) {
Alex Light0e692732017-01-10 15:00:05 -08001590 art::StackHandleScope<2> hs(driver_->self_);
1591 art::Handle<art::mirror::Class> klass(hs.NewHandle(
1592 driver_->self_->DecodeJObject(klass_)->AsClass()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001593 if (klass == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001594 RecordFailure(ERR(INVALID_CLASS), "Unable to decode class argument!");
1595 return false;
1596 }
1597 // Allocate the classExt
Alex Light0e692732017-01-10 15:00:05 -08001598 art::Handle<art::mirror::ClassExt> ext(hs.NewHandle(klass->EnsureExtDataPresent(driver_->self_)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001599 if (ext == nullptr) {
Alex Lighta01de592016-11-15 10:43:06 -08001600 // No memory. Clear exception (it's not useful) and return error.
Alex Light0e692732017-01-10 15:00:05 -08001601 driver_->self_->AssertPendingOOMException();
1602 driver_->self_->ClearException();
Alex Lighta01de592016-11-15 10:43:06 -08001603 RecordFailure(ERR(OUT_OF_MEMORY), "Could not allocate ClassExt");
1604 return false;
1605 }
Alex Light1e3926a2017-04-07 10:38:06 -07001606 // First save the old values of the 2 arrays that make up the obsolete methods maps. Then
1607 // allocate the 2 arrays that make up the obsolete methods map. Since the contents of the arrays
Alex Lighta01de592016-11-15 10:43:06 -08001608 // are only modified when all threads (other than the modifying one) are suspended we don't need
1609 // to worry about missing the unsyncronized writes to the array. We do synchronize when setting it
1610 // however, since that can happen at any time.
Alex Light1e3926a2017-04-07 10:38:06 -07001611 cur_data->SetOldObsoleteMethods(ext->GetObsoleteMethods());
1612 cur_data->SetOldDexCaches(ext->GetObsoleteDexCaches());
1613 if (!ext->ExtendObsoleteArrays(
1614 driver_->self_, klass->GetDeclaredMethodsSlice(art::kRuntimePointerSize).size())) {
1615 // OOM. Clear exception and return error.
1616 driver_->self_->AssertPendingOOMException();
1617 driver_->self_->ClearException();
1618 RecordFailure(ERR(OUT_OF_MEMORY), "Unable to allocate/extend obsolete methods map");
1619 return false;
Alex Lighta01de592016-11-15 10:43:06 -08001620 }
1621 return true;
1622}
1623
1624} // namespace openjdkjvmti